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

查看:61
本文介绍了从指令的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中请求警报"时,它会在$ 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天全站免登陆