2016-06-09 46 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'); 
       } 
      }); 
     } 
    } 
}