Thursday, 17 April 2014

Angular js add class to active element

Here I am going to explain how to add active class on dynamically added content or link while on clicking.

View

 
<ul>

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

 <div>{{ datalist.name }}</div> 

 </li>

 </ul> 
        
 

Controller

 

 $scope.select= function(item) {
        $scope.selected = item; 
 };

 $scope.isActive = function(item) {
        return $scope.selected === item;
 };

 
 

Click on any link, active class will be added to the active element.

Demo

Play in fiddle

But if we need to remove the active class on clicking the item again.Refer this post Add and remove active class on click Angular

Related Posts

1. Angular ng-repeate in directive

2. Loop concept in angular js

3. Angular js client side show more pagination

4. Show and Hide in angular

5. Simple client side sorting in angular


7 comments :

  1. Is there a way to bring the selected item in view? Like , for a long list, the user should not scroll down to see the selected item. It should be right on the screen in view. Any help would be appreciated

    ReplyDelete
  2. This helped me out . Thank you

    ReplyDelete
  3. You did make it easy, Thank you!

    ReplyDelete
  4. Thank U So sooo Much

    ReplyDelete