2014-11-24 404 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); 
});