1

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

1

2 Answers 2

2

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>

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you DonJuwe that works i didn't know that you have to use ng-class with angular
0

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.

1 Comment

Better use ng-class="{active: clickedBoolean}".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.