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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With