Bootstrap: maintaining active state based on routing when manually entering url


Here is a well working plnkr example:

A navigation with 2 links (routing to 2 ui-router states), and a jQuery method that maintains the active class on the active link.


<body ng-app='myApp'>
  <ul class="nav nav-pills">
    <li role="presentation" class="active"><a ui-sref="home">Home</a></li>
    <li role="presentation"><a ui-sref="news">News</a></li>


angular.module('myApp', ['ui.router'])
      $stateProvider.state('home', {
        url : '/home',
        template: '<h1>home</h1>'
      $stateProvider.state('news', {
        url : '/news',
        template: '<h1>news</h1>'



  $(".nav a").on("click", function(){

The app works fine, except, when trying to manually enter the url in the browser navigator, for example if the active tab is Home and I go for http://localhost:8080/news/ the state goes for News, but the active class is still on Home


If you go directly to /news, your function is never executed. It is only executed when a nav link is clicked. You want to execute the function on initial load, as well as whenever the state changes.

A better way to do this would be to avoid jQuery altogether and do things the “Angular way.” You can create a controller for the navbar, and set the active class on the proper elements whenever your state changes.

Answered By – AJ Funk

Answer Checked By – Katrina (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.