In AngularJS, is it possible to pass the source element as a parameter in its ng-class attribute?

499 views Asked by At

Please, consider the following example for understanding my question:

<button ng-class="$scope.controllerMethod($thisButton)" />

In my controllerMethod, I want to get a reference of the button who called ng-class. Is it possible?

(Something like passing $event.target in the ng-click button, so I can read the caller from the controller).

Any helps? Thanks!!

1

There are 1 answers

0
Mark Ni On BEST ANSWER

If you're hard coding each of your button in your menu, you won't need ng-class. Simply ng-click=doSomething('$event'), then the rest is just like your normal Javascript, do whatever you want with $event.target.

If you want do it the angular way, each button needs to have a corresponding model in the controller.

<ul>
   <li ng-repeat='btn in buttons'>
   <button ng-class='{"highlight":btn.clicked}' ng-click='doSomething(btn)'></button>
   </li>
</ul>

In your controller:

$scope.buttons = [{text:'button1'},{text:'button2'}];

$scope.doSomething = function(btn){
   btn.clicked = true;
}

In this example, ng-class will watch each button's clicked property, if it's true, then add highlight class onto this button.