I've got a simple directive that I use to add a class on click and remove it from the element if clicked again. However I'd like to refactor it for a more common use in generic menus. Instead if a <li> element is clicked that is not the current active element, it should remove it from the current element and place it on the new one. Basically I want to add an "active" class to the <li> element that is currently active.
In my menu I have:
<ul>
<li><a swapit ng-click="lol(stillgot)" class="select-show">Still Got Game</a></li>
<li><a swapit ng-click="lol(thick)" class="select-show">TnT</a></li>
<li><a swapit ng-click="lol(seldon)" class="select-show">Seldon</a></li>
<li><a swapit ng-click="lol(hit)" class="select-show">HitMan</a></li>
<li><a swapit ng-click="lol(community)" class="select-show">Community</a></li>
</ul>
.directive('swapit', function() {
return {
restrict : 'A',
link : function(scope, elem) {
var currentState = true;
elem.on('click', function() {
console.log('You clicked me!');
if(currentState === true) {
console.log('It is on!');
angular.element(elem).addClass('active');
} else {
console.log('It is off!');
angular.element(elem).removeClass('active');
}
currentState = !currentState;
});
}
};
});