使用ng-repeat指令的容器的高度为零 [英] Height of container with ng-repeat directive is zero

查看:108
本文介绍了使用ng-repeat指令的容器的高度为零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有ng-repeat指令的div,该指令通过一个数组并将一堆div添加到我的容器中.当我在现在已充满div的容器上调用.height()时,它返回0.它似乎在执行ng-repeat指令之前返回了高度.将ng-repeat指令中的所有元素都添加到DOM后,如何获取高度?

I have a div with an ng-repeat directive that goes through an array and adds a bunch of divs to my container. When I call .height() on the container, which is now filled with divs, it returns 0. It seems to return the height before the ng-repeat directive executes. How can I retrieve the height after all the elements from the ng-repeat directive have been added to the DOM?

我有以下HTML,JS和CSS代码:

I have the following HTML, JS, and CSS code:

HTML:

<!DOCTYPE html>
<html ng-app="myApp">

    <head>
    <link rel="stylesheet" href="style.css">
    </head>

    <body ng-controller="myController">

        <p>Container height: {{containerHeight}}</p>

        <div id="container">
            <div class="box" ng-repeat="box in boxes">
                Box number: {{box}}
            </div>
        </div>

        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
        <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.18/angular.min.js"></script>
        <script src="script.js"></script>
    </body>

</html>

JS:

var myApp = angular.module('myApp', []);


myApp.controller('myController', ['$scope', function($scope) {

    $scope.boxes =
        [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];

    $scope.containerHeight = $('#container').height();

}]);

CSS:

.box
{
    width: 200px;
    height: 200px;
    padding: 10px;
    background-color: skyblue;
    margin: 5px;
}

您可以查看有关我在Plunker上的问题的演示.

推荐答案

http://plnkr .co/edit/g4DfdiKX4HO3qW8kVmsF?p = preview

问题在于,由于DOM呈现是异步的,因此高度是在呈现DOM之前计算的.否则,将在渲染DOM时阻塞您的线程,并且将冻结页面,直到完成昂贵的DOM操作为止.这是事情发生的顺序...

The problem is that the height is being calculated before the DOM is rendered because the DOM rendering is asynchronous. Otherwise, your thread would be blocked while the DOM was rendering and your page would be frozen until the expensive DOM operations are finished. This is the order things are happening...

  1. 实例化控制器,并填充作用域,触发角度$ digest,从而进行DOM更新
  2. 您计算的高度仍为零
  3. 摘要周期结束并且DOM已更新

通过在$ timeout内进行计算,可以将其推到调用堆栈的末尾,在上述步骤3之后并获得正确的高度

By doing the calculation inside a $timeout, you can push it to the end of the call stack, after step 3 above and get the correct height

$timeout(function () {
    // calculate height
});

这篇关于使用ng-repeat指令的容器的高度为零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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