How to show a navigation menu with AngularJS that changes the โ€œactiveโ€ class depending on which route is being viewed?

I just want to show the following in my navigation menu:

<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, by clicking section 1, section 2 or section 3, each of them initiates a route change. Currently, <li> for section 2 has an active class, which means its current active route. I just want to move this class, for example, if the "Section 3" button is clicked, I want the li for section 3 to have an active class.

What is the best way to achieve this?

+4
source share
3 answers

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

Reformat your controller and html as follows:

 $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 to the 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 an example in Plunker .

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

+10
source

Controller function:

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

I achieved this with bootstrap, it can help you

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

Working script here

0
source

Source: https://habr.com/ru/post/1495069/


All Articles