1

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 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

I've never seen bracket notation before. Time to hit the angularjs documentation again. Thanks!
You will not find it in Angular documentation though. You just need to understand that angular expression is basically parsed and evaluated, as javascript. And javascript has this feature: you can access object property with bracket notation: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.