4

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?

3 Answers 3

10

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

Sign up to request clarification or add additional context in comments.

Comments

2

Controller function:

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

Comments

0

I achieved this by using bootstrap, it might help you

$('ul.nav > li').click(function (e) {
        e.preventDefault();
        $('ul.nav > li').removeClass('active');
        $(this).addClass('active');                
    });

The working fiddle is here

2 Comments

This isn't really an angular solution to the problem.
This doesn't work if user hand changes the url from browser's address bar.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.