AngularJS apply class to multiple buttons in mutual exclusive way

Viewed 2078

I'm new to AngularJS, with a jQuery background, and still trying to get into Angular thinking . I've several buttons like :

<button class="btn active">btn1</button>
<button class="btn">btn2</button>
...
<button class="btn">btnN</button>

With jQuery to accomplish my goal, that is to have active class only on one button at time, I would do

jQuery

$(".btn").on('click', function(){
 $(this).siblings().removeClass('active')
        .end()
        .addClass('active');
});

CSS

.active{ ... }

but I did not find out a general way to do this in Angular. I found a solution for 3 buttons, but it gets rude, especially if I have multiple route in my application.

In particular, now the solution I'm using is:

markup

<li class="start" ng:click="selected = 1" ng-class="{active: selected == 1}">
 <a href="#contenuti> </a>
</li>
<li class="start" ng:click="selected = 2" ng-class="{active: selected == 2}">
 <a href="#utenti> </a>
</li>
<li class="start" ng:click="selected = 3" ng-class="{active: selected == 3}">
 <a href="#messaggi> </a> 
</li>

In the CONTROLLER ( for bootstrap settings)

switch($location.path()){
 case '/contenuti/plot': 
  $scope.selected = 1;
  break;
 case '/utenti': 
  $scope.selected = 2;
  break;
 case '/messaggi': 
  $scope.selected = 3;
  break;
}

which is a solution that I don't really love, I don't think is a really good solution. Thanks in advance for helping.

jQuery solution Fiddle: http://jsfiddle.net/HS4d6/

2 Answers
Related