2016-06-09 56 views
0

我试图在特定路由中的元素中应用CSS样式。为此,我创建了一个指令,在$ state.include包含位置时添加类,但由于路径不断变化,因此需要监视$ state中的更改,但不起作用。这里是我的代码:监视指令中的stateParams

angular 
    .module('pharm') 
    .directive('flApplyStyle',['$stateParams','$state',applyStyle]); 

function applyStyle($stateParams,$state) { 
    return { 
     link: function(scope, element, attributes){ 
      console.log($state.current); 
      scope.$watch($stateParams, function (newValue, oldValue) { 
       if ($state.includes("app.calc.edit")) { 
        element.addClass('BackgroundEdit'); 
       }else{ 
        element.addClass('none'); 
       } 
      }); 
     } 
    } 
}; 

回答

0

这应该可能工作。点击进入$stateChangeStart事件,然后检查对$state的更改。如果该事件不起作用,请尝试$stateChangeSuccess

angular 
    .module('pharm') 
    .directive('flApplyStyle', ['$rootScope','$state', applyStyle]); 

function applyStyle($rootScope, $state) { 
    return { 
     link: function(scope, element, attributes){ 
      $rootScope.$on('$stateChangeStart', function() { 
       if ($state.includes("app.calc.edit")) { 
        element.addClass('BackgroundEdit'); 
       } else { 
        element.addClass('none'); 
       } 
      }); 
     } 
    } 
}