Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Is there a way to change the method called by ng-click dynamically?

Something like this:

ng-click = "{{functionCalled}}"

and then declaring the function by:

$scope.functionCalled = "callThisFunction(param)";
share|improve this question

2 Answers 2

up vote 3 down vote accepted

From the docs, ngClick just evaluates the expression in the context of the scope. There's nothing stopping you from referencing a function dynamically, but I'm not sure this is the intended method. I would probably call a function explicitly and switch the behavior based on a parameter instead like ng-click='myFunction(myParams)'. Nonetheless, here's an example of what you what to accomplish. http://jsfiddle.net/8cvGt/2/

HTML

<div ng-app='foo' ng-controller='ctrl'>
    <div ng-click='this[myVar]()'>{{ bar }}</div>
</div>

JavaScript

var app = angular.module('foo',[]).controller('ctrl',function($scope) {
    $scope.myVar = 'callIt';
    $scope.bar = 'before';
    $scope.callIt = function() {
        $scope.bar = 'after';
    }
});
share|improve this answer
    
Great it works thanks, however is there a way I can dynamically set a parameter too? say for a function callit(callId) ? –  FootsieNG Apr 28 at 19:46
1  
Sure, just add your paramater to your call. this[myFunc](myParam) –  Patrick Apr 28 at 19:47
    
I mean so that the parameter takes the value of an ng-model element form the view, such as <input id="inputAns" type="text" data-ng-model="quiz.ans1"></input> –  FootsieNG Apr 28 at 19:56
1  
I updated the fiddle with the scenario I think you're talking about. jsfiddle.net/8cvGt/5 –  Patrick Apr 28 at 20:07
1  
Hmm, yeah I probably wouldn't use this to accomplish that use case. Either a dynamically determined partial for each view ng-include='myViewVariable + "button_section.html"', expand the view to include that section, or have a consistent API between views that it can call like ng-click='done()' and the done function determine what parameters it needs. Hard to tell which is appropriate without knowing more about the app. –  Patrick Apr 28 at 20:36

Assuming you have a set list of possible functions, use a central function to dispatch calls to other functions.

ng-click="dispatchFunction(param)"

Then

$scope.functionToCall = 'callThisFunction';

$scope.dispatchFunction = function(param) {
    switch($scope.functionToCall) {
         case (callThisFunction): callThisFunction(param);
    };

Edit: Actually, use a full dispatch table for this:

http://designpepper.com/blog/drips/using-dispatch-tables-to-avoid-conditionals-in-javascript

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.