我试图在页面加载时正确调整div的大小并在$(window)上调整大小.resize
(但没有jQuery)
我有两套有用的代码:
此解决方案中的第一个:angularJS window resize issue
myapp.directive('resize', function($window) {
return function(scope, element, attr) {
var w = angular.element($window);
w.on('resize', function() {
var hh = document.getElementById('header').offsetHeight;
var fh = document.getElementById('footer').offsetHeight;
console.log('hh & fh', hh, fh);
var tp = hh + 2;
var bt = fh + 2;
console.log('tp & bt', tp, bt);
var changes = {
bottom: bt + 'px',
top: tp + 'px',
}
element.css(changes);
scope.$apply();
});
};
});
...在窗口调整大小时工作正常,但在初始加载/刷新时没有工作
第二个使用链接属性
myapp.directive('contentsize', function($window) {
return {
restrict: 'A',
scope:{},
link:function (scope, element, attrs) {
scope.$watch(function(){return $window.innerHeight;},
function () {
var hh = document.getElementById('header').offsetHeight;
var fh = document.getElementById('footer').offsetHeight;
console.log('hh & fh', hh, fh);
var tp = hh + 2;
var bt = fh + 2;
console.log('tp & bt', tp, bt);
var changes = {
bottom: bt + 'px',
top: tp + 'px',
}
element.css(changes);
},
true);
}
};
});
...在初始加载/刷新时工作正常但在窗口大小调整时没有工作
问题:
- 如何让这些解决方案中的任何一个在初始加载AND window.resize上工作
- 什么是最佳解决方案? (第一个解决方案表明$ watch有不必要的开销)
jsFiddle在这里http://jsfiddle.net/goredwards/012jsvrp/
(只需在html中交换' resize1' for' resize2'以查看第二个'解决方案')
PS div之间的2px空间是故意的。
答案 0 :(得分:2)
为什么不在init
和resize
拨打相同的电话?
myapp.directive('resize', function($window) {
function updateUI(element) {
var hh = document.getElementById('header').offsetHeight;
var fh = document.getElementById('footer').offsetHeight;
console.log('hh & fh', hh, fh);
var tp = hh + 2;
var bt = fh + 2;
console.log('tp & bt', tp, bt);
var changes = {
bottom: bt + 'px',
top: tp + 'px',
}
element.css(changes);
}
return function(scope, element, attr) {
var w = angular.element($window);
updateUI(element);
w.on('resize', function() {
updateUI(element);
scope.$apply();
});
};
});