来自 jQuery 指令的错误元素高度 [英] Wrong element height from a Directive with jQuery

查看:25
本文介绍了来自 jQuery 指令的错误元素高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Angular 的新手,我正在尝试使用 jQuery 从 Directive 进行一些 DOM 计算和操作.然而,我得到的是我元素的错误高度.在我的情况下,元素类似于容器 - 所以高度几乎是视口高度.

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());
        }
    };
}]);

我的身高是 46,这是错误的.当我在控制台中输入时:

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 ?

非常感谢!

推荐答案

指令的 compile 方法在 angular 链接所有模板并呈现它们之前运行.如果您在带有 console.log 的行上放置断点,您将看到这一点.浏览器窗口将几乎是空的,因此注册的高度是正确的.

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.

如果你需要页面的正确高度,在它上面放一个 $watch 并处理它,只要它改变:

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());
        }
    }
  };
}]);

这篇关于来自 jQuery 指令的错误元素高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆