AngularJS使用ng-repeat中的范围变量设置ng-click函数

时间:2014-10-16 17:02:20

标签: angularjs angularjs-ng-repeat angularjs-ng-click

我想在ng-repeat中为ng-click分配不同的功能:

<button ng-repeat="button in notification.buttons" ng-click="button.fn"> {{button.label}} </button>

控制器:

app.controller('MainCtrl', ['$scope', function($scope){
    $scope.notification = {
        ctrl: 'logout', 
        text: 'Logout?',
        buttons: [
                {label:'Yes', fn: 'logout()'},
                {label:'No', fn: 'cancel()'},
        ],
    };
}]);

app.controller('logout', ['$scope', function($scope){
    $scope.logout = function(){
        alert('logout');
    };
    $scope.cancel = function(){
        alert('cancel');
    };
}]);

如果我将button.fn放入双层ng-click="{{button.fn}}"中,生成的html在Chrome检查器中看起来不错,但Angular会抛出以下错误:

  

错误:[$ parse:syntax]语法错误:令牌&#39; button.fn&#39;出人意料,   期待表达式[{{button.fn}}]的第3列的[:]开始   在[button.fn}}]。

如果没有双重曲线,没有错误,但是Angular会像这样生成html并且函数不会被激活:

 <button ng-repeat="button in notification.buttons" ng-click="button.fn" class="ng-binding ng-scope"> Yes logout()</button>

PLUNKER

我有一个关于使用范围变量设置ng-controller的相关问题,使用相同的示例here

1 个答案:

答案 0 :(得分:4)

http://plnkr.co/edit/QE50kpfBjXy2WPvjVsJc?p=preview

我已经创建了代码的分支。你的'fn'引用是字符串。我将它们更改为函数,并将'()'添加到模板中的'button.fn'。我也改变了函数引用的位置,因为函数的定义在不同的控制器中。

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

app.controller('MainCtrl', ['$scope', function($scope){
    $scope.notification = {
        ctrl: 'logout', 
        text: 'Logout?',
        buttons: [
    			{label:'Yes', fn: null},
    			{label:'No', fn: null},
        ],
    };
}]);

app.directive('notification', [
	function() {
		return {
		restrict: 'E', // E = Element, A = Attribute, C = Class, M = coMment
		templateUrl: 'notification.tpl.html',
		replace: true,
		link: function(scope, element, attrs) {
      //...
		}
	};
		
		
}])

app.controller('logout', ['$scope', function($scope){
  $scope.logout = function(){
      alert('logout');
  };
  $scope.cancel = function(){
      alert('cancel');
  };
  
  $scope.notification.buttons[0].fn = $scope.logout;
  $scope.notification.buttons[1].fn = $scope.cancel;
}]);
<div ng-controller="logout">
    <p>{{notification.text}}</p>
    <button ng-repeat="button in notification.buttons" ng-click="button.fn()"> {{button.label}} {{button.fn}}</button>
    <button ng-click="logout()"> Test</button>
</div>