动态网址上的角度活动类

时间:2014-02-15 22:00:46

标签: javascript angularjs angularjs-directive

我正在尝试在我的链接中添加“有效”类:

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

输出:

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

这是我的指示:

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

当我在console.log(attrs.href)时输出#/requests//processes,所以绑定值还没有。

我该如何解决这个问题?

感谢。

1 个答案:

答案 0 :(得分:0)

尝试:

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

但我认为你需要这个:

.directive('active', function($location) {
      return {
        link: function(scope, el, attrs) {
          scope.$watch(function(){
             return '#'+ $location.path() == attrs.href; //always update when one of them changes
          },function(newValue){
             el.toggleClass('active',newValue);
          });
        }
      }
 });