Code Review Stack Exchange is a question and answer site for peer programmer code reviews. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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>'

};
});
share|improve this question

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.