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

6. Add and remove active class on click Angular

7. Add a class for everything clicked - angular

8. Toggle click on dynamic menu items - Angular


10 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
    Replies
    1. You can add some index on selected item and also add sorting on the list. So the selected items will come in top. Hope it is clear.

      Delete
  2. This helped me out . Thank you

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

    ReplyDelete
  4. Thank U So sooo Much

    ReplyDelete
  5. thanks, you save me my day...

    regards.

    ReplyDelete