2015-07-20 115 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 
     }; 
    }); 

这感觉更像是一个解决办法不是解决办法,但我能够继续工作。