Wednesday, 4 May 2016

Add and remove active class on click Angular

Here I have explained (Add class to an active element) about adding a class on click. But if we need to remove the active class on clicking the item again. Let us check how it will work.


 <li ng-repeat="datalist in datalists" ng-click="select(datalist)"
   ng-class="{active: isActive(datalist)}" >
 <div>{{ }}</div> 

Sample JSON

$scope.datalists = [
    { "name": "Read about angular"},
    {"name": "Read about knockout"},
    {"name": "Read about backbone"},
    {"name": "Read about jquery"},
    {"name": "Read about javascript"}


$ function(item) {
  $scope.selected = ($scope.selected === item ? null : item); 
$scope.isActive = function(item) {
  return $scope.selected === item;

Using this approach you can easily find out user is clicking on same item again or not and you can write you're on logic also in this scenario. See the below code for more info.

$ function(item)
  if(item === $scope.selected)
    $scope.selected = null;
    //your logic
    $scope.selected = item;
    //your logic

Related Posts

1. Disable submit button until all mandatory fields are filled - Angular

2. Angular Loader using font awesome icons

3. Angular js add class to active element

4. Add a class for everything clicked - angular

5. Toggle click on dynamic menu items - Angular


  1. How would you handle adding the class to everything clicked? So that all links could turn red if each was clicked?

    1. That is so simple , no need to add any code in controller, just html changes
      li class="paginationclass" ng-repeat="datalist in datalists" ng-click="cliked = true" ng-class="{active: cliked}"


      You can edit the fiddle and check