有一个函数可以处理窗口高度的变化并为元素设置一个新值(相当复杂 - 如果太高则添加/更新滚动,如果不够高则保持固定高度)。 当我调整窗口大小时它效果很好,但在开始时效果不佳。那么,问题来了:如何让它在加载后立即工作?
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);
根本不起作用......困惑,沮丧。
最佳答案
我建议完全避免损害性能的“监视函数的返回值”模式。为什么不直接绑定(bind)到 resize
事件并首先触发该函数?
fitScroll();
angular.element($window).$on('resize', function () {
scope.$apply(fitScroll);
});
关于javascript - 初始窗口大小/调整大小捕获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27106993/