使用来自指令的 ng-click 的警报 [英] Use alert from ng-click of a directive
问题描述
angularjs 的新手.想要将表达式写入 ng-click.
New to angularjs. Want to write an expression into an ng-click.
示例:
x.directive('li',function(){
return {
restrict: 'E',
replace: true,
template: '<games> <game ng-click="(alert({{ game }})" ng-repeat="game in games"> {{ game.team1 }} {{game.bets }} <game></br></games> '
}
});
我想在点击时提醒游戏,但出现此错误:
I want to alert the game on click but I got this error:
Error: [$parse:syntax] Syntax Error: Token 'game' is unexpected, expecting [:] at column 11 of the expression [(alert({{ game }})] starting at [game }})].
推荐答案
当你从 ng-click 请求alert"时,它会在 $scope 上寻找那个方法,但它不存在.
When you ask for 'alert' from ng-click, it looks for that method on the $scope, and it's not there.
请参阅此 plunkr,其中我在范围上使用了一个函数来调用警报指令被点击.
See this plunkr where I used a function on the scope to call the alert when the directive is clicked.
在控制器中我们设置函数:
In the controller we set the function:
$scope.test = function(text) {
alert(text);
}
或者你可以这样做:$scope.alert = alert.bind(window);
.如果你这样做,如果不将上下文绑定到窗口,它将无法工作.
Or you can just do: $scope.alert = alert.bind(window);
. It won't work without binding the context to the window if you do it like that.
在指令的 ng-click 中,我们调用我们的函数:
In the directive's ng-click we call our function:
ng-click="test(game)"
这篇关于使用来自指令的 ng-click 的警报的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!