I'd like to toggle a class when an element is clicked using AngularJS. I need the clicked element to received the class, and any other items in the list to loose the class. I've researched a number of supposed solutions for this on SO, however in implementing them, they don't work appropriately and I don't understand why they would even.
The general solution proposed is to set a variable to the index of the item in the ng-repeat list. Then use ng-class to add the class. JSFiddle here.
<div ng-app>
<p ng-repeat="item in ['a', 'b', 'c']"
ng-click="selectedIndex = $index"
ng-class="{selected: $index === selectedIndex}"
>{{item}}</p>
</div>
The problem is that the 'selected' class is never removed from the previous elements. So, clicking an element adds the class to the element as expected, but clicking another element doesn't remove the class from previously clicked elements. I would guess because Angular is not re-rendering the entire list on each click and thus the old clicked elements don't change. That begs my question though, why is this such an overwhelmingly proposed solution? Am I just implementing something wrong? Thanks.