I've created an AngularJS navigation menu and I'm trying to highlight the active menu item based on ng-repeat.
So far I have the menu working with ng-repeat, but I don't know what to put in the ng-click function for the active class to get applied.
Here's what I have:
Here is my view:
//View (in jade):
ul(ng-controller='MenuCtrl')
li(ng-repeat='navLink in navLinks', ng-click='select(navLink)', ng-class='{active: navLink.linkhref == path}')
a(href='{{navLink.linkhref}}') {{navLink.linktext}}
And here is my controller:
//Controller:
...
controller('MenuCtrl', function ($scope,$location) {
$scope.navLinks = [{
linkhref: '/',
linktext: 'View Dashboard',
}, {
linkhref: '/rpm',
linktext: 'View RPMs',
}, {
linkhref: '/status',
linktext: 'View Status',
}, {
linkhref: '/database',
linktext: 'View Database',
}, {
linkhref: '/config',
linktext: 'View Configurations',
}];
$scope.path = $location.path();
$scope.select = function(navLink) {
//idk what to put here to make the "active" class toggle between nav links
//I could try this:
//remove "active" class from nav links
//then add "active" class to this link
};
})
...
Here's a fiddle with my code:
So far here is the behavior:
- when I go to http://localhost/status, the "View status" link has the "active" class on it. great!
- when I click another link, the "View status" link stays "active", and the new link does not get the "active" class added.
- basically nothing happens when i click, but refreshing the page works (because of the "path == path" thing)
Resources that were helpful:
$scope.pathtonavLink.linkhref(simply because those are what you compare when assigning theactiveclass in yourng-class). jsfiddle.net/bATZ5/2 . However, it's worth noting that this simply makes your solution work. It still has flaw inherent in the original solution (e.g. somewhere on thelielement that is not the link; the route won't change but the active highlight will). You might, instead, want to watch$routeChangeSuccess, or something along those lines.