Skip to content

Instantly share code, notes, and snippets.

@teeaich
Created August 24, 2013 07:32
Show Gist options
  • Save teeaich/6326672 to your computer and use it in GitHub Desktop.
Save teeaich/6326672 to your computer and use it in GitHub Desktop.
Highlight navigation menu object with additional class or/and with arrow positioning of active menu object
'use strict';
// TODO we need a event handler for window.resize to ensure that the
// TODO position will be recalclated
angular.module('flatdesignAngularApp')
.directive('navMenu', ['$compile', function ($compile) {
return {
link: function (scope, element, attrs) {
/*
template used for the arrow
*/
var arrowTemplate = '<span style="display: none;"id="navArrow"></span>';
/*
helper function to get coordinates of the center from specific element
*/
function getNavCoord(navPoint) {
var navElement = element.find('a[data-route="'+navPoint+'"]');
return navElement.offset().left + (navElement.outerWidth() / 2);
}
var links = element.find('a');
var routeMap = {};
var currentLink;
/*
insert the arrow element in DOM
*/
element.children().first().before(arrowTemplate);
var arrowElement = element.find('#navArrow');
$compile(arrowElement)(scope);
/*
build object map for all links with data-attribute 'route'
*/
for (var i = 0; i < links.length; i++) {
routeMap[$(links[i]).data('route')] = links[i];
}
/*
register route change event to position the arrow and highlight the link
*/
scope.$on('$routeChangeSuccess', function (event, next) {
var location = next.$$route.pagekey;
if (routeMap[location]){
arrowElement.css('display','inline');
if(currentLink){
$(currentLink).removeClass('active');
}
currentLink = routeMap[location];
$(routeMap[location]).addClass('active');
var coord = getNavCoord(location);
arrowElement.css('left',coord);
} else {
if(currentLink){
$(currentLink).removeClass('active');
}
arrowElement.css('display','none');
}
});
}
};
}]);
<nav nav-menu>
<a data-route="todo" href="/#todo">Todo</a>
<a data-route="assets" href="/#assets">Assets</a>
</nav>
'use strict';
angular.module('flatdesignAngularApp', [])
.config(['$routeProvider',function ($routeProvider) {
//$locationProvider.html5Mode(true);
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl',
pagekey: 'root'
})
.when('/todo', {
templateUrl: 'views/todo.html',
controller: 'TodoCtrl',
pagekey: 'todo'
})
.when('/assets', {
templateUrl: 'views/assets.html',
controller: 'AssetsCtrl',
pagekey: 'assets'
})
.otherwise({
redirectTo: '/'
});
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment