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>

And then in JavaScript:

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

I have setup up a simple jsfiddle to demonstrate the problem:

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:

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

Answered By – Hengjie

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published