adding and removing classes in angularJs using ng-click
I want to add or remove "active
" class in my code dynamically on ng-click
, here what I have done.
<ul ng-init="selectedTab = 'users'"> <li ng-class="{'active':selectedTab === 'users'}" ng-click="selectedTab = 'users'"><a href="#users" >Users</a></li> <li ng-class="{'active':selectedTab === 'items'}" ng-click="selectedTab = 'items'"><a href="#items" >Items</a></li></ul>
You just need to bind a variable into the directive "ng-class" and change it from the controller. Here is an example of how to do this:
var app = angular.module("ap",[]);app.controller("con",function($scope){ $scope.class = "red"; $scope.changeClass = function(){ if ($scope.class === "red") $scope.class = "blue"; else $scope.class = "red"; };});
.red{ color:red;}.blue{ color:blue;}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script><body ng-app="ap" ng-controller="con"> <div ng-class="class">{{class}}</div> <button ng-click="changeClass()">Change Class</button> </body>
Here is the example working on jsFiddle
There is a simple and clean way of doing this with only directives.
<div ng-class="{'class-name': clicked}" ng-click="clicked = !clicked"></div>