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

4. Add a class for everything clicked - angular

5. Toggle click on dynamic menu items - Angular

3 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