Angular Js - Get Element Height In Directive Before View Render
Solution 1:
Wrap your call to $scope.setHeight() in a $timeout call.
In essence $timeout without a delay will happen after your DOM has loaded and so the values will be ready to use.
Solution 2:
You can take advantage of $timeout like this:
app.directive('valign', ['$window', '$timeout', function ($window, $timeout) {
return {
link: function ($scope, $element) {
var window = angular.element($window);
$scope.setHeight = function () {
var contentHeight = window.height() - $('#header').outerHeight(true) - $('#footer').outerHeight(true);
// Here I want to get the $element height so I can set the proper margin for it, for example
};
$timeout($scope.setHeight, 500, true);
window.bind('resize', function () {
$scope.setHeight();
$scope.$apply();
});
}
};
}]);
Basically, what we're doing is to trigger the setHeight function after a delay of 500 ms during which we hope the directive to render. We can increase/decrease the time based on individual requirements.
Solution 3:
Solved!
I used Andy Lewis & Sidharth Panwar suggestion and warped my my function call in $timeout with 0ms that insures that the function runs after DOM is ready + I changed the markup so the valign directive would be INSIDE and ng-view (ui-view in my case), that made the changes apply BEFORE the view enter transition.
Final code is:
app.directive('valign', ['$window', '$timeout', function ($window, $timeout) {
return {
link: function ($scope, $element) {
var window = angular.element($window);
$scope.setHeight = function () {
var contentHeight = window.height() - $('#header').outerHeight(true) - $('#footer').outerHeight(true);
$element.css('margin-top',(contentHeight - $element.outerHeight(true)) /2);
};
$timeout($scope.setHeight, 0);
window.bind('resize', function () {
$scope.setHeight();
$scope.$apply();
});
}
};
}]);
and markup:
<div ui-view>
<div valign></div>
</div>
Post a Comment for "Angular Js - Get Element Height In Directive Before View Render"