Wrong element height from a Directive with jQuery

2019-07-20 05:28发布

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条回答
劳资没心,怎么记你
2楼-- · 2019-07-20 06:09

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());
        }
    }
  };
}]);
查看更多
登录 后发表回答