0

In angular.js how can I toggle a css class active on and off on click of the element? I know I can use ng-class and ng-click but how do I reference itself? For example, let's say I have three buttons:

<a class="btn" ng-click="" ng-class"">First</a>
<a class="btn" ng-click="" ng-class"">Second</a>
<a class="btn" ng-click="" ng-class"">Third</a> 

1 Answer 1

1
<a ng-click="firstActive = !firstActive" ng-class"{'btn':true, 'active':firstActive}">First</a>
<a ng-click="secondActive = !firstActive" ng-class"{'btn':true, 'active':secondActive}">Second</a>
<a ng-click="thirdActive = !firstActive" ng-class"{'btn':true, 'active':thirdActive}">Third</a> 

You'll have to have separate scope variables in your controller for firstActive, secondActive, and thirdActive, all set to false by default.

Sign up to request clarification or add additional context in comments.

2 Comments

Is there a way without explicitly setting all these flags and polluting the controller?
I don't see it as "polluting" the controller. The controller is supposed to hold display logic and data linkage, and that is exactly what this is. If you don't want to do it this way, try using the Angular-UI buttons.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.