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.

HTML


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

Sample JSON


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

Controller


$scope.select= 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.


$scope.select= function(item)
{
  if(item === $scope.selected)
  {
    $scope.selected = null;
    //your logic
  }else
  {
    $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

1 comment :

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

    ReplyDelete