[英]Angular ng-click
Learning the AngularJS. 学习AngularJS。 Trying to change an example from tutorial.
尝试从教程中更改示例。 Need ng-init value be equals to the value transmitted from script function.
需要ng-init值等于从脚本函数传输的值。 How it can be done?
怎么做? Code is below:
代码如下:
<html>
<body>
<h2>AngularJS Sample Application</h2>
<div ng-app="mainApp" ng-controller="clickController">
<p>Total click: {{ click.clickCounter() }}</p>
<button ng-click="count = count+1"
ng-init="count=click.clickCounter()">Click Me!</button>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
</script>
</body>
<script>
var mainApp = angular.module("mainApp", []);
mainApp.controller('clickController', function($scope) {
$scope.click = {
count: 15,
clickCounter: function() {
var foo;
foo = $scope.click;
return foo.count;
}
};
});
</script>
</html>
Problem is with transfering the value of click.clickCounter() to ng-click. 问题是将click.clickCounter()的值传输到ng-click。
You issue is your are creating a new count
variable on the root of your scope. 您的问题是您正在作用域的根上创建一个新的
count
变量。
Your count vaiable if $scope.click.count
however the ng-init
ang ng-click
are creating and updating $scope.count
. 如果
$scope.click.count
但是ng-init
ng-click
正在创建和更新$scope.count
。
this fixes the issue 这解决了问题
<button ng-click = "click.count = click.count+1" ng-init="click.count=click.clickCounter()">Click Me!</button>
EDIT: If you add {{count}}
inside your app you will see the scope variable it is creating. 编辑:如果在应用程序内添加
{{count}}
,您将看到它正在创建的范围变量。 One of the double edged swords of Angular is if you define variables in your view that don't exist on your scope Angular will create and add them to the scope for you. Angular的双刃剑之一是,如果您在视图中定义了范围中不存在的变量,Angular将为您创建并将其添加到范围中。
EDIT 2: Your ng-init
is obsolete. 编辑2:您的
ng-init
已过时。 Seeing as you already created a count
property of your $scope.click
object it is already initialized and has a value. 好像您已经创建了
$scope.click
对象的count
属性一样,它已被初始化并具有一个值。
Also see fiddle: http://jsfiddle.net/yjwskkat/ 另请参阅小提琴: http : //jsfiddle.net/yjwskkat/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.