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> </ul> </div>
Using $location.path() we get the current route. The substring operation removes the leading slash (/) and converts /home to home
[ad#post]
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' : ''; }; }]);
Code