2013-02-15 58 views
1

我正在尝试使用角度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

回答

4

改变你的表达

count = count + 1 

解决了这个问题。演示:Fiddle

由于Angular不使用eval来评估表达式,所以不能在其中使用完整的JavaScript范围;这是这些例外之一。如果您需要一些更强大的,你可以通过一个JavaScript函数来$apply(演示:Fiddle):

scope.$apply(function() { 
    scope.count++; 
}); 
3

为什么不直接使用ng-click

<body ng-controller='MainCtrl'> 
    <button ng-click="increment()" value="Increment Me!"> 
    <h1>{{count}}</h1> 
</body> 

而在你的JS:

function MainCtrl($scope) { 
    $scope.count = 0; 
    $scope.increment = function() { $scope.count++; }; 
} 
相关问题