Wrong element height from a Directive with jQuery

蹲街弑〆低调 提交于 2019-12-11 02:53:07

问题


I'm new to Angular and I'm trying to do some DOM calculations and manipulations from Directive using jQuery. What I've got however is wrong height of my element. In my case the element is something like container - so the height almost all the viewport height.

directives.directive('responsiveAlerts', ['$log', '$window', function ($log, $window) {
    return {
        restrict: 'A',
        compile: function (element, attributes) {
            console.log($('.page').height());
        }
    };
}]);

I've got 46 as a height, which is wrong. When I type in the console:

$('.container').height();

since the page is loaded - I'm getting the right height of my container. Has anybody have idea why there is such a difference ?

many thanks in advance!


回答1:


The compile method of a directive runs before angular links all the templates and renders them. You will see this, if you put a breakpoint at the line with console.log. The browsers window will be almost empty then and the registered height is therefor correct.

If you need the correct height of the page, put a $watch on it and handle it, whenever it changes:

directives.directive('responsiveAlerts', ['$log', '$window', function ($log, $window) {
  return {
    restrict: 'A',
    link: function ($scope) {
        var elPage = angular.element('.page');
        $scope.$watch(elPage.height, function () {
             console.log(elPage.height());
        }
    }
  };
}]);


来源:https://stackoverflow.com/questions/24513382/wrong-element-height-from-a-directive-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!