I have created a directive which is doing several things, all revolved around adding and active class to navigation elements when clicked. It also adds the class when someone goes directly to the url. I'm fairly new to writing directives and this one seems like it would be something I'd like to reuse in future projects. Is there a more concise and reusable way I could be writing this logic?
app.directive('navigation', function ($location, $timeout) {
return {
restrict: 'E',
scope: {
hoverClass:'@'
},
link: function (scope, element, attrs) {
scope.$on("$routeChangeSuccess", function (event, current, previous) { //routeChangeSuccess
var location = (current.$$route.originalPath);
var locationSplit = ("/" + location.split('/')[1]);
var selectionhref = element.children().find('a');
//Searches for match of routepath url and href, removes siblings active, adds active
(function(){
element.children().each(function(index){
console.log(location);
if($(selectionhref[index]).attr('href') == (locationSplit)){
$(this).siblings().removeClass('active');
$(this).addClass('active');
};
});
})()
}); //routeChangeSuccess
element.children().mouseover(function(){ //add remove on hover
$(this).addClass('hover');
}).mouseout(function(){
$(this).removeClass('hover');
}); //add remove on hover
element.children().click(function(){ //add remove on click
var ref = $(this);
$timeout(function() {
var loc = $location.path();
var relative = ref.children().attr("href");
if (loc == relative){
ref.addClass('ractive');
}
ref.siblings().removeClass('active');
ref.addClass('active');
}, 1);
});
}, //add remove on click
template: '<li hover-class="yellow" class="yellow"><a href="/">Home</a></li>' +
'<li hover-class="red" class="red"><a ng-href="/about">About</a></li>' +
'<li hover-class="green" class="green"><a ng-href="/services">Services</a></li>' +
'<li hover-class="orange" class="orange"><a ng-href="/events">Calendar</a></li>' +
'<li hover-class="red" class="red"><a ng-href="/volunteer">Volunteer</a></li>' +
'<li hover-class="green" class="green"><a ng-href="/contact">Contact</a></li>' +
'<li hover-class="red" class="red"><a ng-href="/blog">Blog</a></li>'
};
});