Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show a navigation menu with AngularJS which changes 'active' class depending on which route is being viewed?

I simply want to show a navigation menu like the following in my app:

<ul>
  <li><a href="#/section1">Section 1</a></li>

  <li class="active"><a href="#/section2">Section 2</a></li>

  <li><a href="#/section3">Section 3</a></li>
</ul>

Here, clicking section 1, section 2, or section 3 will each trigger a route change. Currently the <li> for section 2 has the class active which means its the currently active route. I simply want to move this class around, so e.g if Section 3 is clicked, I want the li for section 3 to have the active class.

What's the best way to achieve this?

like image 704
Ali Avatar asked Dec 15 '22 07:12

Ali


2 Answers

You could listen to $routeChangeSuccess event (see documentation for $route) to detect changes.

Reformat your controller and html like this:

$scope.navList = [
  { url: '/route1', title: 'Route 1'},
  { url: '/route2', title: 'Route 2'},
  { url: '/route3', title: 'Route 3'}
];

<ul>
  <li ng-repeat="item in navList">
    <a ng-class="{active:item.active}" href="#{{item.url}}">{{item.title}}</a>
  </li>
</ul>

And then listen for changes (in your controller):

function detectRoute() {
  angular.forEach($scope.navList, function(item) {
    item.active = $location.path().match(new RegExp(item.url)) ? true : false;
  });  
}

$scope.$on('$routeChangeSuccess', detectRoute);

See example in Plunker.

I wrapped this up in a module: https://github.com/Espesen/angular-simple-navbar

like image 111
Esa Toivola Avatar answered Apr 30 '23 05:04

Esa Toivola


Controller function:

...
$scope.isActive = function (viewLocation) {
  return viewLocation === $location.path();
};
...
like image 34
velaskec Avatar answered Apr 30 '23 05:04

velaskec