Pass the reference to the DOM object using ng-click

I have several elements with the same ng-click callback:

<button ng-click="doSomething()"></button> <button ng-click="doSomething()"></button> <button ng-click="doSomething()"></button> <button ng-click="doSomething()"></button> 
 // In controller: $scope.doSomething = function() { // How do I get a reference to the button that triggered the function? }; 

How can I get a reference to the object that made the doSomething call? (I need to remove attr from it)

+59
angularjs angularjs-ng-click
Jun 21 '13 at 16:49 on
source share
2 answers

The angular way is shown in the angular docs :)

https://docs.angularjs.org/api/ng/directive/ngReadonly

Here is an example that they use:

 <body> Check me to make text readonly: <input type="checkbox" ng-model="checked"><br/> <input type="text" ng-readonly="checked" value="I'm Angular"/> </body> 

Basically, the angular way is to create a model object that will contain whether the input should be read-only, and then set this model object accordingly. The beauty of angular is that most of the time you do not need to do any manipulations with dom. You simply angular render the view the way your model is installed (let angular do the dom manipulations for you and keep your code clean).

So basically in your case you would like to do something like below or check out this working example.

 <button ng-click="isInput1ReadOnly = !isInput1ReadOnly">Click Me</button> <input type="text" ng-readonly="isInput1ReadOnly" value="Angular Rules!"/> 
+21
Jun 23 '13 at 4:09
source share

While you are doing the following, technically speaking:

 <button ng-click="doSomething($event)"></button> 
 // In controller: $scope.doSomething = function($event) { //reference to the button that triggered the function: $event.target }; 

This is probably what you don't want to do, since the AngularJS philosophy is to focus on model manipulation and let AngularJS do the rendering (based on the prompts from the declarative interface). Manipulating DOM elements and attributes from a controller is a big no-no in the AngularJS world.

You can check this answer for more information: stack overflow

+201
Jun 21 '13 at 16:54
source share



All Articles