Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

angularjs - Use alert from ng-click of a directive

New to angularjs. Want to write an expression into an ng-click.

example:

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 }})].
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When you ask for 'alert' from ng-click, it looks for that method on the $scope, and it's not there.

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);
}

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.

In the directive's ng-click we call our function:

 ng-click="test(game)"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...