If I have a navbar in bootstrap with the items
Home | About | Contact
How do I set the active class for each menu item when they are active? That is, how can I set class="active"
when the angular route is at
#/
for home#/about
for the about page#/contact
for the contact page
First and foremost, this problem can be solved in a lot of ways. This way might not be the most elegant, but it cerntainly works.
Here is a simple solution you should be able to add to any project. You can just add a "pageKey" or some other property when you configure your route that you can use to key off of. Additionally, you can implement a listener on the $routeChangeSuccess method of the $route object to listen for the successful completion of a route change.
When your handler fires you get the page key, and use that key to locate elements that need to be "ACTIVE" for this page, and you apply the ACTIVE class.
Keep in mind you need a way to make ALL the elements "IN ACTIVE". As you can see i'm using the .pageKey class on my nav items to turn them all off, and I'm using the .pageKey_{PAGEKEY} to individually turn them on. Switching them all to inactive, would be considered a naive approach, potentially you'd get better performance by using the previous route to make only active items inactive, or you could alter the jquery selector to only select active items to be made inactive. Using jquery to select all active items is probably the best solution because it ensures everything is cleaned up for the current route in case of any css bugs that might have been present on the previous route.
Which would mean changing this line of code:
to this one
Here is some sample code:
Given a bootstrap navbar of
And an angular module and controller like the following:
JavaScript
HTML
This is long answered but I thought I'd share my way:
Template:
For those using
ui-router
:For exact match (eg nested states?) use
$state.name === 'full/path/to/state'
orui-sref-active-eq="active"
Here's a simple approach that works well with Angular.
Within your AngularJS controller:
This is a simple solution
In conjunction with @Olivier's AngularStrap answer, I also implemented kevinknelson's answer from: https://github.com/twbs/bootstrap/issues/9013.
Natively, the Bootstrap3 navbar was not designed for a single-page (eg Angular) application and thus the menu when on a small screen was not collapsing upon click.