Monday 27 February 2017

Toggle click on dynamic menu items - Angular

Let us check how we can add class to all clicked elements and to remove the same on another click. It is pretty straight forwarded in Angular js. In the previous articles I have explained about adding class on the active elements with different scenario. If interested you can check those as well.

Let us check how we can achieve this.

Sample Array


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

Html


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

Js


$scope.select= function(item) {
  this.selected = (this.selected === item ? null : item); 
};
$scope.isActive = function(item) {
  return this.selected === item;
};

CSS


 .active{color : red;}

Click the below link and see the result

Related Post

1. Angular js add class to active element

2. Add and remove active class on click Angular

3. Add a class for everything clicked - angular

5 comments :

  1. awesome, thanks.

    ReplyDelete
  2. How to work in Angular 2 same code please give an example

    ReplyDelete
    Replies
    1. http://www.angulartutorial.net/2017/04/add-class-to-active-element-angular-2.html

      Delete
  3. Toggle click on dynamic menu items - Angular 2 Need
    I used this code but not working

    selected:any;
    datalists:any;

    ngOnInit(){
    this.datalists = [
    { "name": "Read about angular"},
    {"name": "Read about knockout"},
    {"name": "Read about backbone"},
    {"name": "Read about jquery"},
    {"name": "Read about javascript"}
    ]
    }
    select(item):void {
    this.selected = (this.selected === item ? null : item);
    };
    isActive(item){
    return this.selected === item;
    };

    ReplyDelete
    Replies
    1. http://www.angulartutorial.net/2017/04/add-class-to-active-element-angular-2.html

      http://www.angulartutorial.net/2017/12/5-different-ways-for-conditionally.html

      Delete