So i am trying to add / remove a class from a list item all depending on a variable: (Note if there is a better of doing this active thing please let me know :P )
So my code looks like this:
<li ng-repeat="fold in folds" class="{{selectedFolder == fold.filter ? 'active' : ''}}">
<a ng-click="selectedFolder = fold.filter">
{{fold.name}}
</a>
</li>
Now when i click the first one the class is added however once i click the next one the old class is not replaced by '' instead now two li has the class active
Can anyone tell me why?
You can use ng-class
<li ng-repeat="fold in folds" ng-class="{'active' : selectedFolder == fold.filter}">
.....
</li>
this will add the css class active to the li element when selectedFolder == fold.filter is sets to true, IF selectedFolder == fold.filter is sets to false then active class is remove from the li element.
if you need to toggle the css class add & remove when clicking, I think you can remove the .. ng-click="selectedFolder = fold.filter"... part and replace it with ng-click="selectedFolder = !selectedFolder" and change the ng-class to ng-class="{'active' : selectedFolder == 1} and add ng-init="selectedFolder = 0" to the li, This will add a variable to ng-repeat scope so that each repeat has its own selectedFolder variable in its scope (ng-repeat creates a child scope).
when click in <a> we can toggle the value of selectedFolder so that will toggle the css class ..<a ng-click="selectedFolder = !selectedFolder">..
here is the DEMO
UPDATE
to having one active element.
create a variable to refer the active element. (I used object because its easy to refer from the ng-repeat because ng-repeat creates a child scope, so we cant directly call if this variable is just a primitive variable if its primitive we have to use $parent.variable_name), So its easy to use a object to represent it.
$scope.active = {
elm : -1
}
when click on <a> assign the $index value to active.elm
<a ng-click="active.elm = $index">
..
$index is the ng-repeat index just like
for first repeat $index is equals to 0
for second repeat $index is equals to 1.. like wise.
change ng-class to, this will add class active when active.elm == $index set to true.
..ng-class="{'active' : active.elm == $index}">
...
here is the DEMO
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With