How can I make an angularjs button click call a passed-in function?

时间:2016-04-21 21:50:01

标签: angularjs

I'm trying to make an application that has some data-driven UI. So, I'm trying to pass in a function that should be called when a button is clicked. The second button works, of course, as it explicitly calls the function. However, the first one doesn't. Here's the angular js code:

$scope.clickFunction = "clickedIt()";
$scope.clickedIt = function(){
    alert("It worked!");}

And the html:

<p>How can I make this button call a passed-in function?</p>
<button ng-click="{{clickFunction}}">Click Me</button>
<p>I'd like it to evaluate to this, which works.</p>
<button ng-click="clickedIt()">Click Me</button>

Here's a plunker with the code I'm try to make work. http://plnkr.co/edit/aRBX3bbgHCV15mgROZx1?p=preview

1 个答案:

答案 0 :(得分:1)

You need to define a function name in controller you want to use as event handler:

$scope.clickFunction = "clickedIt";

then in template use bracket notation:

<button ng-click="this[clickFunction]()">Click Me</button>

The idea is that this points to current scope object, exactly what you want, and that's why bracket notation is useful here.

Demo: http://plnkr.co/edit/TmdGuCpnbYz3gaWDi9tB?p=preview