Pregunta

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)";
¿Fue útil?

Solución

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';
    }
});

Otros consejos

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

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top