adding and removing classes in angularJs using ng-click


I am trying to work how to add a class with ngClick. I have uploaded up my code onto plunker Click here. Looking at the angular documentation i can’t figure out the exact way it should be done. Below is a snippet of my code. Can someone guide me in the right direction

 <div ng-show="isVisible" ng-class="{'selected': $index==selectedIndex}" class="block"></div>


var app = angular.module("MyApp", []);
app.controller("subNavController", function ($scope){

        $scope.toggle = function (){
            $scope.isVisible = ! $scope.isVisible;

        $scope.isVisible = false;


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",[]);

  $scope.class = "red";
  $scope.changeClass = function(){
    if ($scope.class === "red")
      $scope.class = "blue";
      $scope.class = "red";

<script src=""></script>
<body ng-app="ap" ng-controller="con">
  <div ng-class="class">{{class}}</div>
  <button ng-click="changeClass()">Change Class</button>    

Here is the example working on jsFiddle

Answered By – geonunez

Answer Checked By – Marie Seifert (AngularFixing Admin)

Leave a Reply

Your email address will not be published.