So I have a directive for when the page loads that will resize the content to fit the correct dimensions. However, when the page loads there's a service call that populates the model of this specific section of content and when I obtain the height of this element, its size is 0 because the model wasn't updated at the point of resizing. I'm trying to resize as soon as the page loads so the user doesn't notice elements moving around on the screen, but it's not really possible if the size of the element is decided after the model is updated.
Is there any way to calculate the height of the section post-digestion or get a proper height pre-digestion?
myApp.directive('resize', function() {
return function(scope, element) {
var htmlHeight = angular.element("html").height();
var headerHeight = angular.element("#page-header").height();
var dashboardHeight = angular.element(".top-dashboard").height(); // Returns 0 because of pre-loaded data not existing
var totalHeight = htmlHeight - headerHeight - dashboardHeight;
scope.$on('$viewContentLoaded', function() {
element[0].style.height = totalHeight + 'px';
});
}
});
The html with the directive on it:
<section class="top-dashboard row full" resize>
<div class="small-3" ng-include src="'partials/location.html'"></div>
</section>
Update 1: I thought doing a resolve to have the data before the controller loaded would take care of it, but the height is still returning 0.
Update 2: Maybe this is more of an issue with the fact that it's a template that's being included? Especially seeing as wrapping it in timeout didn't help at all, nor doing a resolve.
Couple of things. Don't bother with ng-style at all, you've got direct access to the element. Use that. Also, you're watching htmlHeight which is just a pixel value but you never assigned it to the scope anyway... so I'm not sure what you're trying to do here but that won't work because you're watching scope.htmlHeight which I don't see defined anywhere.
Where is the controller that calls the service to populate the partial? That's where you'd want to $emit or $broadcast an event to let your directive know it needs to redraw. If the controller is above the directive, use $scope.$broadcast('resizeMe'); otherwise use $scope.$emit the same way.
Then in your directive you can just do something like this
myApp.directive('resize', ['$timeout', function($timeout) {
return function(scope, element) {
var $html = angular.element("html"),
$header= angular.element("#page-header"),
$dash= angular.element(".top-dashboard");
var resize = function(){
var totalHeight = $html.height() - $header.height()- $dash.height();
element.style.height = totalHeight + 'px';
}
scope.$on('resizeMe', function(){
$timeout(resize); //forces it to wait till the next digest
});
}
}]);
No real need for any watches or anything like that here. Try to avoid adding watches.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With