Join the Stack Overflow Community
Stack Overflow is a community of 6.6 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

I want to remove active class from an li and add it to another li. I know how to do it with jQuery but I don't know how to make it work with AngularJS.

Here is my code :

$(document).ready(function() {

    // event to nav bar header
    $("ul.nav li").click(function() { 

        $("ul.nav li").removeClass("active");
        $(this).addClass("active");
    });
});

Demo Here

share|improve this question
    
Please look at the ng-class documentation docs.angularjs.org/api/ng/directive/ngClass – Sphaso Mar 9 '15 at 11:52
up vote 2 down vote accepted

You can build up an array of your nav items in your scope and call a function which sets a variable to true if the respective string matches.

Furthermore, I suggest building your nav with ng-repeat based on this very array.

var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {
  
    var navArr = [
        'home',
        'help',
        'admin'
    ];
    
    $scope.setNavActive = function(str) {
      console.log(str);
        angular.forEach(navArr, function(item) {
          console.log(item);
          $scope[item] = (str == item);
        });
    };
    
    $scope.home = true;
}
.nav-pills > li.active > a, .nav-pills > li.active > a:hover, .nav-pills > li.active > a:focus {
  color: #fff;
  background-color: #6da54d;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>

<div ng-app="myApp" ng-controller="MyCtrl">
  <ul class="nav nav-pills pull-right mynavbar">
    <li ng-class="{active: home}" ng-click="setNavActive('home')"><a ng-href="#/">Home</a></li>
    <li ng-class="{active: help}" ng-click="setNavActive('help')"><a ng-href="#/help">Help</a></li>
    <li ng-class="{active: admin}" ng-click="setNavActive('admin')"><a ng-href="#/administration">Administration</a></li>
  </ul>
</div>

share|improve this answer
    
Thank you DonJuwe that works i didn't know that you have to use ng-class with angular – Maher Mahouachi Mar 9 '15 at 14:02

I like to use the ternary operator

ng-class="(clickedBoolean) ? 'active' : ''"

Just change clickedBoolean to whatever your click event is changing and your ng-class directive will act accordingly.

share|improve this answer
1  
Better use ng-class="{active: clickedBoolean}". – Miraage Mar 9 '15 at 12:00

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.