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?
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
Controller function:
...
$scope.isActive = function (viewLocation) {
return viewLocation === $location.path();
};
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With