Reputation: 2494
I'm trying to get a div to size correctly on page load AND also resize on $(window).resize
(but without jQuery)
I've got two sets of code that kinda work :
The 1st from this solution: 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();
});
};
});
...which works fine on window resize, but not on initial load / refresh
The 2nd uses a link property
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);
}
};
});
...which works fine on initial load / refresh but not on window resize
Questions:
- how do I get either of these solutions to work on initial load AND window.resize
- What's the optimum solution ? (1st solution indicates that $watch has unnecessary overhead)
jsFiddle is here http://jsfiddle.net/goredwards/012jsvrp/
(just swap the 'resize1' for 'resize2' in the html to see the 2nd 'solution')
PS The 2px space between divs is deliberate.
Upvotes: 1
Views: 4594
Reputation: 14440
Why don't you just call the same function at init
and 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();
});
};
});
Upvotes: 2