-2
.. ng-repeat
<li ng-class="{'active':selIndex==$index}">
<span ng-click="selIndex=$index">click</span>
</li>

The problem with above code is, it doesn't reset all the li's class before adding active class to the clicked one. How to apply removeClass logic in angluarjs?

Jennifer
  • 905
  • 9
  • 20

2 Answers2

2

You don't actively remove a class in Angular. You tell Angular under which circumstances which class must be active, and it will figure it out. You do that with ng-class, as you do. If the condition is true, the class will be present on the element, else it won't. Whenever any state changes, Angular recalculates all the classes for all the elements. Classes will be removed by Angular as soon as the condition for it becomes false.

More likely your logic doesn't work somewhere. I wouldn't use $index for anything, since the index of any one item might change at any time. Rather use the data itself:

$scope.items = [{ id: 1 }, { id: 2 }];
$scope.activeItem = null;
$scope.selectItem = function (item) {
    $scope.activeItem = item;
}
<li ng-repeat="item in items" ng-class="{ active: item.id == activeItem.id }">
    <span ng-click="selectItem(item)">

Using direct assignment inside ng-click directives can get tricky in terms of scope; using a function on the controller typically works without any issues.

deceze
  • 510,633
  • 85
  • 743
  • 889
  • this work like accordian. I want to have a button that can remove the acitive class. – Jennifer Feb 05 '16 at 15:06
  • Not that if it's difficult to put it on the controller e.g. the ng-repeat is nested inside another ng-repeat then you can use ng-init to create the 'activeItem' variable – Mike Jerred Feb 05 '16 at 15:07
  • @Jennifer then just set activeItem = null ... – Mike Jerred Feb 05 '16 at 15:07
  • @Jennifer No you don't want to remove classes. You want to *model your state on the `$scope`*, then set up your view to present that state accordingly. That means anyone should be able at any time to look at your `$scope` and get the idea what's currently going on **purely from the data present there.** Don't think in terms of adding or removing anything in the view "by hand" directly. – Most likely you want a button *that sets the current active item to `null`.* – deceze Feb 05 '16 at 15:08
  • what is the activeItem.id come from? – Jennifer Feb 05 '16 at 15:14
  • @Jennifer From the `item` passed to the `selectItem` function. Which is one of the `items`. – deceze Feb 05 '16 at 15:31
0

This might be related to ng-repeat that creates a child scope for each iteration.

You should try the following :

<li ng-class="{'active':$parent.selIndex==$index}">
    <span ng-click="$parent.selIndex=$index">click</span>
</li>

If you have nested ng-repeat, it will become a hell to debug. I recomend you to use the controller as syntax : https://stackoverflow.com/a/21292408/1251861

Community
  • 1
  • 1
Deblaton Jean-Philippe
  • 11,188
  • 3
  • 49
  • 66