How to set bootstrap navbar active class with Angular JS?

Matheus Mello
Matheus Mello
September 2, 2023
Cover Image for How to set bootstrap navbar active class with Angular JS?

How to Set Bootstrap Navbar Active Class with Angular JS?

So you want to set the active class for each menu item in a Bootstrap navbar when the AngularJS route is active? No worries, I got you covered! 🙌

The Problem 🤔

When creating a navbar using Bootstrap in combination with AngularJS, setting the active class can be a bit tricky. You want the correct menu item to be highlighted when the user is on a specific page, based on the AngularJS route.

The Solution 💡

Here's a simple solution to set the active class for each menu item in your navbar:

  1. Start by adding the ngRoute module to your AngularJS application. This module is responsible for handling routes and updating the active class.

  2. In your HTML file, define your navbar structure using the Bootstrap classes. For example:

<nav class="navbar navbar-expand-lg navbar-light bg-light">
    <a class="navbar-brand" href="#">Logo</a>
    <ul class="navbar-nav mr-auto">
        <li class="nav-item">
            <a class="nav-link" href="#/">Home</a>
        </li>
        <li class="nav-item">
            <a class="nav-link" href="#/about">About</a>
        </li>
        <li class="nav-item">
            <a class="nav-link" href="#/contact">Contact</a>
        </li>
    </ul>
</nav>

Note the use of the ng-href directive instead of the regular href attribute. This allows us to use AngularJS expressions in the href value.

  1. In your AngularJS configuration, define the routes for your application using the $routeProvider. For example:

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

app.config(function($routeProvider) {
    $routeProvider
        .when('/', {
            templateUrl: 'home.html',
            controller: 'HomeController'
        })
        .when('/about', {
            templateUrl: 'about.html',
            controller: 'AboutController'
        })
        .when('/contact', {
            templateUrl: 'contact.html',
            controller: 'ContactController'
        })
        .otherwise('/');
});

Make sure to include the appropriate controllers and templates for each route.

  1. Next, create a custom AngularJS directive to handle the active class. This directive will add the "active" class to the menu item if the route matches. Add the following code to your JavaScript file:

app.directive('activeNav', function($location) {
    return {
        restrict: 'A',
        link: function(scope, element) {
            scope.$on('$routeChangeSuccess', function() {
                var path = $location.path();
                angular.forEach(element.find('a'), function(link) {
                    var href = link.getAttribute('href');
                    if (path === href) {
                        angular.element(link).addClass('active');
                    } else {
                        angular.element(link).removeClass('active');
                    }
                });
            });
        }
    };
});
  1. Finally, apply the active-nav directive to your navbar element. This will activate the directive and add/remove the "active" class based on the current route. Update your HTML code as follows:

<nav class="navbar navbar-expand-lg navbar-light bg-light" active-nav>
    <!-- Navbar content -->
</nav>

And that's it! Your Bootstrap navbar will now automatically update the active class based on the AngularJS route.

Conclusion 🎉

Setting the active class for each menu item in a Bootstrap navbar with AngularJS can initially seem challenging, but with a few simple steps, you can achieve the desired functionality. Just remember to include the ngRoute module, define your routes, create a custom directive, and apply it to your navbar. Your users will now have a visually satisfying and user-friendly experience while navigating your website. Happy coding! ✨

Was this guide helpful? Have you encountered any issues or challenges while setting the active class? Let me know in the comments below! And don't forget to share this post with your fellow developers to spread the knowledge. 👍

Take Your Tech Career to the Next Level

Our application tracking tool helps you manage your job search effectively. Stay organized, track your progress, and land your dream tech job faster.

Your Product
Product promotion

Share this article

More Articles You Might Like

Latest Articles

Cover Image for How can I echo a newline in a batch file?
batch-filenewlinewindows

How can I echo a newline in a batch file?

Published on March 20, 2060

🔥 💻 🆒 Title: "Getting a Fresh Start: How to Echo a Newline in a Batch File" Introduction: Hey there, tech enthusiasts! Have you ever found yourself in a sticky situation with your batch file output? We've got your back! In this exciting blog post, we

Cover Image for How do I run Redis on Windows?
rediswindows

How do I run Redis on Windows?

Published on March 19, 2060

# Running Redis on Windows: Easy Solutions for Redis Enthusiasts! 🚀 Redis is a powerful and popular in-memory data structure store that offers blazing-fast performance and versatility. However, if you're a Windows user, you might have stumbled upon the c

Cover Image for Best way to strip punctuation from a string
punctuationpythonstring

Best way to strip punctuation from a string

Published on November 1, 2057

# The Art of Stripping Punctuation: Simplifying Your Strings 💥✂️ Are you tired of dealing with pesky punctuation marks that cause chaos in your strings? Have no fear, for we have a solution that will strip those buggers away and leave your texts clean an

Cover Image for Purge or recreate a Ruby on Rails database
rakeruby-on-railsruby-on-rails-3

Purge or recreate a Ruby on Rails database

Published on November 27, 2032

# Purge or Recreate a Ruby on Rails Database: A Simple Guide 🚀 So, you have a Ruby on Rails database that's full of data, and you're now considering deleting everything and starting from scratch. Should you purge the database or recreate it? 🤔 Well, my