Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angularjs pass anonymous function through ng-click

I am using AngularJS and would like to pass an anonymous JavaScript function from an html element's ng-click function as a parameter to a function on my scope.

<div ng-app="">
  <div ng-controller="Ctrl1">
      <button ng-click="test(function(){alert('pushed');})">Push Me</button>
  </div>
</div>

And then in JavaScript:

function Ctrl1($scope) {
    $scope.test = function(callback){
        callback();
    };
}

I have setup up a simple jsfiddle to demonstrate the problem: http://jsfiddle.net/C4t4LystX/gUj8x/4/


Whenever I try and do this in my code I get this type of error in the console:

Syntax Error: Token '{' is unexpected, expecting [)]

How should I perform this?

like image 633
psionicgames Avatar asked Nov 04 '22 10:11

psionicgames


1 Answers

In JavaScript, you'd want to evaluate the function that you would like to run. In this case, if you'd like to execute the instructions alert("pushed") then you'd want to evaluate that string.

I've developed a JS Fiddle that does this here: http://jsfiddle.net/gUj8x/6/

Note that the instruction is now passed to Angular as an quote-escaped string.

like image 140
Hengjie Avatar answered Nov 11 '22 13:11

Hengjie