Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use alert from ng-click of a directive

Tags:

angularjs

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 }})].
like image 202
AME Avatar asked Sep 18 '14 08:09

AME


1 Answers

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)"
like image 156
Nitsan Baleli Avatar answered Oct 13 '22 07:10

Nitsan Baleli