我正在尝试使用 Angular js 编写指令,其中单击按钮必须增加一个count
值。
在单击事件处理程序上,我尝试使用scope.$apply
构造增加值,但它Syntax Error: Token 'undefined' not a primary expression at column NaN of the expression [count++] starting at [count++]
在控制台中引发错误。
标记
<div ng-app="myApp">
<div ng-controller="MainCtrl">
<div my-directive >
</div>
</div>
</div>
JS
var myApp = angular.module('myApp', []);
myApp.directive('myDirective', function(){
return {
scope: {},
template: '<div>{{count}}</div><input type="button" class="increment" value="Increment" />',
link: function(scope, iElement, iAttrs, controller) {
console.log('link', scope.count)
iElement.on('click', '.increment', function(){
console.log('click', scope.count);
scope.$apply('count++');
})
},
controller: function($scope){
console.log('controller')
$scope.count = 0;
}
};
});
myApp.controller('MainCtrl', ['$scope', function($scope){
}]);
演示:小提琴