使用来自指令的 ng-click 的警报 [英] Use alert from ng-click of a directive

查看:21
本文介绍了使用来自指令的 ng-click 的警报的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆