Select navigation menu base on page url in AngularJS

I come across a scenario in my current angular project where I need to select navigation menu base on page url.

Here is my menu

 <div class="well sidebar-nav" ng-app="app">
   <ul class="nav nav-list" ng-controller="navCtrl">
     <li ng-class="navClass('home')"><a href='#/home'>Home</a></li>
     <li ng-class="navClass('about')"><a href='#/about'>About Us</a></li>
     <li ng-class="navClass('contact')"><a href='#/contact'>Contact Us</a></li>

Using $location.path() we get the current route. The substring operation removes the leading slash (/) and converts /home to home

 var app = angular.module('app', []);
  app.controller('navCtrl', ['$scope', '$location', function ($scope, $location) {
            $scope.navClass = function (page) {
                var currentRoute = $location.path().substring(1) || 'home';
                return page === currentRoute ? 'active' : '';


Leave a Reply