I need to make sure the correct menu item is highlighted according to which URL is currently being viewed.
Now the problem with our site is that each menu item can represent several pages. So the Client menu will show the client list - but should still be highlighted when you go to the edit client page. So I can't parse the current URL and match it against the menu item to determine if it should be highlighted.
Instead I have decided to add a custom field - menu
- to the $routeProvider setup. So when setting up the routes :
$routeProvider
.when(
'/SecurityGroup/Index',
{
templateUrl: '/SecurityGroup/IndexPartial',
controller: 'GroupListController',
menu: 'group'
}
)
.when(
'/SecurityGroup/MemberClients/:groupId&:groupName',
{
templateUrl: '/SecurityGroup/MemberClientsPartial',
controller: 'MemberClientsController',
menu: 'group'
}
)
Then in the HTML, the menus are specified as (the tr-menu attribute matches against the name field in the route) :
<li menuitem tr-menu="group" href='/SecurityGroup/IndexPartial'>Groups</li>
<li menuitem tr-menu="client" href='/Clients/IndexPartial'>Clients</li>
Then I have a directive that manages the menu highlighting - essentially adding and removing the Active class if the current route contains the correct name :
(function() {
'use strict';
angular.module('Administration')
.directive('menuitem', ['$location', function($location) {
return {
restrict: 'A',
scope: false,
transclude: true,
replace: false,
template: '<a ng-transclude></a>',
link: function (scope, element, attrs) {
var href = attrs.href;
var name = attrs.trMenu;
var link = element.find('a');
link.attr('href', href);
scope.$on('$routeChangeSuccess', function (event, currentRoute, previousRoute) {
var menu = currentRoute.$$route.menu;
if (menu === name)
element.addClass('active');
else
element.removeClass('active');
});
}
};
}]);
}());
Is this a clever solution, or a terrible abuse of javascripts dynamic abilities? Is there a more Angular way of doing things rather than relying on adding my own fields to the existing Angular data structures?