Rise Leonardo
Rise Leonardo

Reputation: 23

Changing the class of the navigation menu in Angular js

Hi i have this menu in my angular js project, how can i make so, that the current class will change depending to what is clicked.

<ul>
   <li class="current"><a href="#menu1">Menu 1</a></li>
   <li><a href="#menu2">Menu 2</a></li>
   <li><a href="#menu3">Menu 3</a></li>
   <li><a href="#menu4">Menu 4</a></li>
</ul>

I have following code in my aplication.js

var app = angular.module('tutorialWebApp', [
    'ngRoute'
]);

app.config(['$routeProvider', function ($routeProvider) {
    $routeProvider
        .when("/menu1", {templateUrl: "menu1.html"})
        .when("/menu2", {templateUrl: "menu2.html"})
        .when("/menu3", {templateUrl: "menu3.html"})

}]);

Upvotes: 1

Views: 66

Answers (1)

Alex Doe
Alex Doe

Reputation: 934

You can add your menu in a controller and then to use ng-class function for each link separately https://docs.angularjs.org/api/ng/directive/ngClass


Here it is an example:

html: (replace with you current code)

<nav ng-controller="navController">
 <ul>
   <li ng-class="menuClass('menu1')"><a href="#menu1">Menu 1</a></li>
   <li ng-class="menuClass('menu2')"><a href="#menu2">Menu 2</a></li>
   <li ng-class="menuClass('menu3')"><a href="#menu3">Menu 3</a></li>
   <li ng-class="menuClass('menu4')"><a href="#menu4">Menu 4</a></li>
 </ul>
</nav>

js: (add this at the end of your app.js file)

app.controller('navController', function($scope, $location) {
    $scope.menuClass = function(page) {
        var current = $location.path().substring(1);
        return page === current ? "current" : "";
    };
});

Upvotes: 1

Related Questions