AME
AME

Reputation: 2302

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 }})].

Upvotes: 19

Views: 40804

Answers (1)

Nitsan Baleli
Nitsan Baleli

Reputation: 5458

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)"

Upvotes: 43

Related Questions