2015-07-20 57 views
-1

我有一個使用其父元素的計算樣式來計算其自身寬度的指令。getComputedStyle()在使用離子框架時在角度指令中不起作用

第一次加載包含該指令的視圖時,我得到了父元素的正確計算樣式。但在此之後,每當我再次加載相同的視圖時,我都會遇到錯誤的風格。

我認爲這必須與離子中的緩存有關,但當我關閉視圖的緩存並關閉全局緩存時,我會遇到同樣的問題。任何想法我失蹤?

這是我在做什麼要點:

angular.module('app.directive') 

    .directive('myDirective', function ($window) { 

     var link = function (scope, element, attrs) { 
      var elementStyleMap = $window.getComputedStyle(element.parent()[0], null); 
      var paddingTop = elementStyleMap.getPropertyValue("padding-top").replace("px", ""); 
      // first time this is called, padding top is 10px, which is correct 
      // all subsequent times the view is loaded and this is called, padding top is 1px 
     }; 

     return { 
      restrict: 'E', 
      replace: true, 
      templateUrl: 'path/to/template.html', 
      link: link 
     }; 
    }); 

回答

2

我以$timeout執行任何代碼試圖訪問的計算方式後的DOM完成加載解決了這個。

我的代碼現在看起來是這樣的:

angular.module('app.directive') 

    .directive('mydirective', function ($window, $timeout) { 

     var link = function (scope, element, attrs) { 

      $timeout(function() { 
       var elementStyleMap = $window.getComputedStyle(element.parent()[0], null); 
       var paddingTop = elementStyleMap.getPropertyValue("padding-top").replace("px", ""); 
      }); 

     }; 

     return { 
      restrict: 'E', 
      replace: true, 
      templateUrl: 'path/to/directive.html', 
      link: link 
     }; 
    }); 

這感覺更像是一個解決辦法不是解決辦法,但我能夠繼續工作。

相關問題