【发布时间】:2014-12-12 03:35:11
【问题描述】:
我想在 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] 语法错误:令牌 'button.fn' 是意外的, 在表达式 [{{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>
我有一个关于使用范围变量设置 ng-controller 的相关问题,这个例子与 here 相同。
【问题讨论】:
-
ng-click 期待一个函数(IE button.fn()),而不是你得到的指针。这就是它不会火的原因。我见过的唯一选择是创建一个指令。见This。
标签: angularjs angularjs-ng-repeat angularjs-ng-click