I'm trying to apply a class to only one element at a time (see this plunk).
HTML:
<ul>
<li ng-repeat="item in listItems">
<a ng-class="{'userActive': isActive, 'userInactive': !isActive}" ng-click="isActive = !isActive">L</a>
<a ng-class="{'userActive': isActive, 'userInactive': !isActive}" ng-click="isActive = !isActive">R</a>
<a ng-class="{'userActive': isActive, 'userInactive': !isActive}" ng-click="isActive = !isActive">J</a>
</li>
</ul>
JS:
var app = angular.module("testApp", []);
app.controller("MainController", function($scope) {
$scope.listItems = [{description: 'item1', number: 1}];
});
Right now, when I click an element in this list, the class toggle is applied to all elements.
I want to be able to click and unclick each letter to toggle the class change individually. How can I do this?
Maybe this:
you need to use three varaibles for ng-class, using one will reflect everywhere
if you want to use only one varaible
The difficulty is that in your case all list elements share the same scope, so when you set
isActive
there is no way to distinguish which one is actually should be active.The simple solution to me is to isolate scope for every item. Maybe this is not nicest solution, but pretty simple with the help of very tiny directive:
Where
isolate
directive is defined as: