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
If you would rather not use AngularStrap then this directive should do the trick!. This is a modification of https://stackoverflow.com/a/16231859/910764.
JavaScript
HTML
Note: The above HTML classes assume you are using Bootstrap 3.x
You can actually use angular-ui-utils'
ui-route
directive:or:
Header Controller
Index page
If you're using ui-utils, you may also be interested in ui-router for managing partial/nested views.
You can achieve this with a conditional in an angular expression, such as:
That being said, I do find an angular directive to be the more "proper" way of doing it, even though outsourcing a lot of this mini-logic can somewhat pollute your code base.
I use conditionals for GUI styling every once in a while during development, because it's a little quicker than creating directives. I couldn't tell you an instance though in which they actually remained in the code base for long. In the end I either turn it into a directive or find a better way to solve the problem.
I just wrote a directive to handle this, so you can simply add the attribute
bs-active-link
to the parent<ul>
element, and any time the route changed, it will find the matching link, and add theactive
class to the corresponding<li>
.You can see it in action here: http://jsfiddle.net/8mcedv3b/
Example HTML:
Javascript:
You can also use this active-link directive https://stackoverflow.com/a/23138152/1387163
Parent li will get active class when location matches /url:
If you are working with Angular router, the RouterLinkActive directive can be used really elegantly: