Wednesday 4 May 2016

Conditionally add or remove 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

4. Add a class for everything clicked - angular

5. Toggle click on dynamic menu items - Angular

4 comments :

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

    ReplyDelete
    Replies
    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}"

      css
      .active{color:red;}

      You can edit the fiddle and check

      Delete
  2. http://www.angulartutorial.net/2017/02/add-class-for-everything-clicked-angular.html

    ReplyDelete
    Replies
    1. Have you ever done something where you have multiple filters on 1 page but only 1 filter is active at a time. So if user clicks a filter, you want to update class of all other filters so they don't appear to be active? I have an icon that is displayed to show that filter is active, so if user clicks to use a filter, I need to change the class of all of the other filters on the page...

      Delete