2014-11-24 402 views
0

具有一個函數,用於查看窗口高度變化併爲元素設置一個新值(非常複雜 - 如果太高則添加/更新滾動,如果滾動不夠高則保持固定高度)。 當我調整一個窗口的大小時,它的效果很好,但不是在開始時。所以,這裏有一個問題:如何在加載之後立即工作?初始窗口大小/調整大小

angular.module('main') 
    .directive('blablaRightColumnViewPort', ['$window', 
     function($window, $timeout) { 

      var directive = {}; 
      directive.restrict = 'A'; 

      directive.compile = function(element, attributes) { 

       // DOM references 
       var w = angular.element($window),... 
        maxHeight = 0; 

       function fitScroll() { 
        // count max height available 
        maxHeight = ...; 

        // compare an original size of the content to max available 
        if (originalElementHeight > maxHeight) { 
         element.height(maxHeight); 
        } else { 
         element.height(originalElementHeight); 
        } 
       } 

       return function(scope, element, attributes) { 

        // watch it! 
        scope.$watch(function() { 
         return w.height(); 
        }, function(){ 
         ... 
         fitScroll(); 

        }); 

        // assign the event 
        w.bind('resize', function() { 
         scope.$apply(); 
        }); 
       } 
      } 

      return directive; 
     } 
    ]); 

我試圖編譯使用:

   $timeout(function(){ 
        w.resize(); 
       }, 0); 

和鏈接:

   $timeout(function(){ 
        scope.$apply(); 
       }, 0); 

沒有工作在所有...困惑,沮喪。

回答

1

我建議避免性能傷害「觀看函數的返回值」模式。爲什麼不只是綁定到resize事件,並最初觸發該功能?

fitScroll(); 
angular.element($window).$on('resize', function() { 
    scope.$apply(fitScroll); 
});