2016-05-23 88 views
1

如何通过使用Angular按钮来更改视图中的某个变量?如何在angularJS中按下按钮时更改变量?

例如观点:

<div id="someDiv" ng-app="myApp" ng-controller="myCtrl"> 
    <p ng-bind="firstname"></p> 
    <button type="button" ng-click="changeValue('Joe')"></button> 
</div> 

脚本:

var app = angular.module('myApp', []); 
     app.controller("myCtrl", function($scope){ 
     $scope.firstname = "Johny"; 

     $scope.changeValue= function(param) { 
     $scope.firstname = param; 
     } 
     }); 

我希望当我按下按钮,然后代替约翰尼拉将是乔(如参数)。 在当我按一下按钮没有任何时刻发生


@EDIT 好吧,我知道问题出在哪里。这在我的主要分区工作正常。然而,它并不在我的第二个div工作:

我点击另一个按钮运行下面的脚本,该脚本改变了我的div

function show(div_id){ //div_id is `someDiv` 
     document.getElementById('main_place').innerHTML = document.getElementById(div_id).innerHTML; 
     } 

但为什么角脚本无法在这个div工作?

+2

要调用从您的视图“changeValue”,但在控制器内的功能名称是“hidePrefs”。你是这样做还是错字? – Rambler

+0

只是错字,已编辑。 – DiPix

+0

你的代码工作正常。编辑错字时尝试测试它。 –

回答

0

请检查之一。

HTML:

<div id="someDiv" ng-app="myApp" ng-controller="myCtrl"> 
    <p ng-bind="firstname"></p> 
    <button type="button" ng-click="changeValue('Joe')"></button> 
</div> 

JS:

var myApp = angular.module('myApp',[]); 

myApp.controller("myCtrl", function($scope){ 
    $scope.firstname = "Johny"; 

    $scope.changeValue= function(param) { 
    $scope.firstname = param; 
    } 
}); 

我创建了您的问题,工作示例:

http://jsfiddle.net/halirgb/Lvc0u55v/

0

添加

$scope.changeValue = function(newVal) { 
    $scope.firstname = newVal; 
} 

而且对HTML把<p>{{firstname}}<p>

0

试试这个在控制器:

$scope.changeValue = function(changeName) 
{ 
$scope.firstname = changeName; 
}; 

在View:

<p>{{firstname}}</p> 
+0

为什么在同一时间使用braket和ng-bind? –

+0

@DiPix试试这个: – Priyank

+0

是啊!我已经更新了我的答案。 – Priyank

0

这里是一个工作示例

var app = angular.module('myApp', []); 
app.controller("myCtrl", function($scope){ 
    $scope.firstname = "Johny"; 
    $scope.changeValue = function(param) { 
     $scope.firstname = param; 
    } 
}); 

<html> 
<head> 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script> <link rel="stylesheet" href="style.css" /> 
<script src="script.js"></script> 
</head> 

<body> 
    <div id="someDiv" ng-app="myApp" ng-controller="myCtrl"> 
    <p ng-bind="firstname"></p> 
    <button type="button" ng-click="changeValue('Joe')">Click</button> 
    </div> 
</body> 

</html> 

https://plnkr.co/edit/dz553Og6E83wx0LF6NHT?p=preview

相关问题