BonJon
BonJon

Reputation: 799

How to setup the class in my case

I am trying to add the class by ng-class in my app.

I have something like

html

 <li   ng-repeat="item in items"
       ng-click="getItem(item)"
       ng-class="{shine : item.isPick}"  // shine class will make the font color change to red
        >{{item.name}}
</li>

In my controller

$scope.getItem = function(item) {
    $scope.items.forEach(function(item){
       item.isPick = false;  // remove all the items that have shine class
    })
    item.isPick = true; // adding the shine class back
}

Basically I want to remove every other 'shine' class except the selected item when user clicks it. My codes above work but I am thinking there is a better way to do it instead of looping all the items. Can someone help me about it? Thanks a lot!

Upvotes: 0

Views: 36

Answers (1)

tymeJV
tymeJV

Reputation: 104775

Use the $index in the repeater, and add the class when that index is selected:

<li ng-repeat="item in items"
   ng-click="getItem($index)"
   ng-class="{shine : activeIndex == $index}"
    >{{item.name}}
</li>

$scope.getItem = function(index) {
    $scope.activeIndex = index;
}

Upvotes: 3

Related Questions