最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - angularjs pass anonymous function through ng-click - Stack Overflow

programmeradmin1浏览0评论

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: /


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?

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/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?

Share Improve this question edited Aug 6, 2021 at 18:10 ruffin 17.5k11 gold badges96 silver badges149 bronze badges asked Nov 28, 2012 at 22:08 psionicgamespsionicgames 2374 silver badges8 bronze badges 2
  • 1 This is not supported in AngularJS, functions should be defined on a scope before being used in a template. What are you trying to do, functionally speaking? – pkozlowski.opensource Commented Nov 28, 2012 at 22:20
  • Basically I have a directive that handles popups and has an isolated scope and when the popup is closed it emits an event up to a higher level scope that closes the dialog and calls a callback function. The callback function is different depending on which popup is closing, thus my need for a callback function being passed in from the html. This way my directive can stay generic and handle popups of any type, seeing as the callback is defined in the html and not in the directive. – psionicgames Commented Nov 28, 2012 at 22:29
Add a ment  | 

1 Answer 1

Reset to default 2

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/gUj8x/6/

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

发布评论

评论列表(0)

  1. 暂无评论