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>
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>
Use a switch with ternary operator as follow
<button ng-model="toggle" ng-class="toggle ? 'red' : ''" ng-click="toggle=!toggle">Change Class</button>
ng-click="toggle=!toggle": When clicked on button the value of toggle will be reversed and updated in the same variable.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>
ng-click="function()" with a function. Can I use two ng-clicks, one for the function and another for ng-click="toggle=!toggle"?ng-clicks.
ng-modelworks. buttons aren't attached to data. Instead, you should removeng-modelentirely and useng-clickto change the state of the data, like the answer provided by @Tushar