Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular md-nav-bar to reflect current route

Tags:

angularjs

I use the following md-nav-bar:

<md-nav-bar md-selected-nav-item="currentNavItem" aria-label="nav">
    <md-nav-item md-nav-href="#/overview" name="overview">Übersicht</md-nav-item>
    <md-nav-item md-nav-href="#/howitworks" name="howitworks">So funktioniert's</md-nav-item>
    <md-nav-item md-nav-href="#/startnow" name="startnow">Jetzt loslegen</md-nav-item>
</md-nav-bar>

I would like the nav bar to reflect the current URL's route, so if the URL is http://somewhere/#/howitworks the second md-nav-item should be highlighted. So far I was not able to find out how to go about it.

like image 485
Onestone Avatar asked Jan 21 '26 16:01

Onestone


1 Answers

(I can't post a comment, so I have to post this as a response)

$location.path() is not working for you because the path is not changing, but the hash (the part after the #). You have to use $location.hash() instead.

ng-class="{YOUR_CLASS: $location.hash() === 'YOUR_PATH'}"

If you prefer to use md-selected-nav-item, as I do, you can add a function to the controller to extract the name of the tab from the hash:

this.getTabName() {
    return $location.hash().replace(/(^#\/|\/$)/g, '');
}

Then your can use it in your view in this way:

<md-nav-bar md-selected-nav-item="getTabName()" aria-label="nav">
    <md-nav-item md-nav-href="#/overview" name="overview">Übersicht</md-nav-item>
    <md-nav-item md-nav-href="#/howitworks" name="howitworks">So funktioniert's</md-nav-item>
    <md-nav-item md-nav-href="#/startnow" name="startnow">Jetzt loslegen</md-nav-item>
</md-nav-bar>
like image 106
jcarrenog Avatar answered Jan 24 '26 09:01

jcarrenog



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!