Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)";
like image 968
FootsieNG Avatar asked Apr 28 '14 19:04

FootsieNG


People also ask

Can we put condition in NG-click?

We can add ng-click event conditionally without using disabled class.

Can we use NG-click and Onclick together?

For a single btn, it's ok to use ng-click or onclick in the ng-app . There is no difference between the two functions. For effective team work, you,d better to have an account with each other. In Angular apps, ng-click is recommended.

Can Ng-click have two functions?

In this article, we will learn how to get many/multiple functions to the ng-click directive passed, in just one click. The key is to add a semi-colon (;) or a comma (,). All the functions must be separated by a (;) or a (, ). This syntax is supported by all the elements in the HTML.

How can you bind an element to data in AngularJS?

Two-way Binding Data binding in AngularJS is the synchronization between the model and the view. When data in the model changes, the view reflects the change, and when data in the view changes, the model is updated as well.


1 Answers

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';
    }
});
like image 163
Patrick Avatar answered Oct 12 '22 22:10

Patrick