我正在嘗試使用角度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){
}]);
演示:Fiddle