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

Issue

Here is a well working plnkr example: http://plnkr.co/edit/p45udWaLov388ZB23DEA?p=preview

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

index.html

<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>
  </ul>
  <ui-view></ui-view>
</body>

app.js

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

});

script.js

$(document).ready(function(){
  $(".nav a").on("click", function(){
    $(".nav").find(".active").removeClass("active");
    $(this).parent().addClass("active");
 });
});

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

Solution

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.