Angularjs - add class to a link based on url with binding

2

I'm trying to add an 'active' class to my link as follows:

<a href="#/requests/{{request.id}}/processes" active>Processes</a>

That produces output (chrome console)

<a href="#/requests/7cgSiSdaIR/processes" active="">Processes</a>

This is my directive:

.directive('active', function($location) {
  return {
    link: function(scope, el, attrs) {
      if('#'+$location.path() == attrs.href) {
        el.addClass('active');
      }
    }
  }
})

When I get the value of attrs.href via console.log, it is #/requests//processes , that is, the binding has not yet been implemented.

How can I resolve this?

    
asked by anonymous 15.02.2014 / 23:13

1 answer

2

The class verification and addition code is right. The problem is when it runs.

When the linking function is running, the value of request.id is not yet "7cgSiSdaIR".

To make sure of this, check the value of scope.request.id via console.log, in the same place where you previously checked the value of attrs.ref .

You see this value in the output (chrome console) because later the value of request.id becomes "7cgSiSdaIR" and, because of binding , the attribute href is updated.

Suggestion:

.directive('active', function($location) {
  return {
    link: function(scope, el, attrs) {
      scope.$watch('request.id', function() {
        if('#'+$location.path() == el.attr('href')) {
          el.addClass('active');
        }
      });
    }
  }
})

In this way, you will check if you want to add the class when the value of request.id is assigned, and no longer when linking .

    
16.02.2014 / 19:41