AngularJS - using data binding {{}} in ng-click

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

Something like that:

ng-click = "{{functionCalled}}" 

and then declaring a function:

 $scope.functionCalled = "callThisFunction(param)"; 
+7
javascript angularjs data-binding single-page-application angularjs-ng-click
source share
2 answers

From docs, ngClick simply evaluates the expression in the scope context. There is nothing stopping you from dynamically referencing the function, but I'm not sure if this is the assigned method. I would call the function explicitly and switch the behavior based on the parameter, and not like ng-click='myFunction(myParams)' . However, here is an example of what you should do. 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'; } }); 
+8
source share

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

 ng-click="dispatchFunction(param)" 

Then

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

Change Actually use the full distribution table for this:

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

+3
source share

All Articles