Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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> 

Controller

var app = angular.module("MyApp", []); app.controller("subNavController", function ($scope){          $scope.toggle = function (){             $scope.isVisible = ! $scope.isVisible;         };          $scope.isVisible = false;     }); 
like image 921
NewKidOnTheBlock Avatar asked Dec 08 '13 23:12

NewKidOnTheBlock


People also ask

How do I delete a class in AngularJS?

You could have ng-click that can toggle selected flag, that could be use with ng-class to bind / unbind class. You could easily do this by using ng-repeat which will reduce your line of code.

What is Ng-click in AngularJS?

The ng-click directive tells AngularJS what to do when an HTML element is clicked.


2 Answers

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> 
like image 65
cutedevil086 Avatar answered Sep 24 '22 11:09

cutedevil086


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

like image 44
geonunez Avatar answered Sep 25 '22 11:09

geonunez