简体   繁体   中英

Angular routes & active links

I'm trying to make selected link on navigation bar highlighted based on current location in the url. For that I have written following function in controller for navbar:

$scope.isActive = function(route) {
  return route === $location.path();
};

and in html I have this:

<li ng-class="{active: isActive('/admin')}"><a href="/admin">Admin</a></li>

This works well for simple url but does not perform well for urls with id and subpaths. I mean if I have url as 'item/:id' it does not match in isActive function and does not get highlighted, also I want to highlight same li for multiple sub routes like item menu should be highlighted for items & items/:id & items/my . Any idea how can I achieve this?

try this

<li ng-class="{isActive('/admin')? 'active' : ''}"><a href="/admin">Admin</a></li>

or

$scope.getActiveClass = function(route) {
  return (route === $location.path())? 'active' : '';
};


//in directive
<li ng-class="getActiveClass ('/admin')"><a href="/admin">Admin</a></li>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM