1

I want to use the predefined AngularJS Directives to toggle a class on click without having to write JavaScript code.

I tried to toggle class by using ng-class:

<button ng-model="toggle" ng-class="{'red' : toggle}">Change Class</button>

codepen

1
  • that's not how ng-model works. buttons aren't attached to data. Instead, you should remove ng-model entirely and use ng-click to change the state of the data, like the answer provided by @Tushar Commented Nov 11, 2015 at 12:16

1 Answer 1

5

Use a switch with ternary operator as follow

<button ng-model="toggle" ng-class="toggle ? 'red' : ''" ng-click="toggle=!toggle">Change Class</button>
  1. ng-click="toggle=!toggle": When clicked on button the value of toggle will be reversed and updated in the same variable.
  2. The ternary operation in ng-class will check if the toggle is truthy, then add class red else it removes the class.

Demo:

.red {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
  <button ng-model="toggle" ng-class="toggle ? 'red' : ''" ng-click="toggle=!toggle">Change Class</button>
</div>


You can also use

<button ng-model="toggle" ng-class="{'red' : toggle}" ng-click="toggle=!toggle">Change Class</button>

.red {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
  <button ng-model="toggle" ng-class="{'red': toggle}" ng-click="toggle=!toggle">Change Class</button>
</div>

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

3 Comments

Thank you so much! but I have an ng-click="function()" with a function. Can I use two ng-clicks, one for the function and another for ng-click="toggle=!toggle"?
@Fuiba You can add the toggling in the function itself. No need of two ng-clicks.
@Fuiba - inside ng-click is just javascript, so if you are not allowed to touch the js files, you can still call the function e.g. ng-click="toggle=!toggle; myFunction()"

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.