angularjs ng重复表,高度错误

时间:2014-08-27 14:06:11

标签: angularjs angularjs-ng-repeat

我有一个问题,就是在页面加载时获取ngRepeat表的高度

我试图在事件$ viewContentLoaded触发时获取高度,但是表格的高度等于表格标题栏的高度。我的表看起来像这样:

http://media-cache-ak0.pinimg.com/originals/d9/cc/70/d9cc70b55e750d92f17685e8c57692b7.jpg

如何获得正确的桌子高度?非常感谢。

这是我的代码:

$scope.$on('$viewContentLoaded', function(){
    var elem = angular.element(document.getElementById('ng-repeat-table-test'));
    console.log(elem.height());
});

Chrome Developer工具测量的实际桌面高度为234px。但是,上面的代码打印出100px,这是标题栏的高度。

更多代码:

用于呈现表格的代码:

 <table id="ng-repeat-table-test">
     <tr id="title">
         <td>Car Types</td>
     </tr>
     <tr class="row" ng-repeat="car in cars">
         <td>{{car.name}}</td>
     </tr>
  </table>

CSS:

table{
    margin-left: auto;
    margin-right: auto;
    margin-top: 10px;
}
tr#title{
    height: 100px;
    background-color: #ccc;
}
tr.row{
    padding-top: 10px;
    border-top: 1px solid #ccc;
}
tr.row:first-child{
    border-top: none;
}
tr.row td{
    padding-top: 10px;
    height: 56px;
    vertical-align: top;
}

jsfiddle

上的小块代码

1 个答案:

答案 0 :(得分:2)

当Angular完成编译时会激活$ viewContentLoaded,这并不意味着浏览器已经渲染了DOM。

所以在你的情况下,问题是当$ viewContentLoaded的回调被执行时,表格还没有画出任何行,这就是你得到错误高度的原因。

尝试延迟(移动到队列末尾)使用$ timeout执行该操作,因此可以在获得元素高度之前操纵DOM。

$scope.$on('$viewContentLoaded', function(){
  $timeout(function () {
     var elem = angular.element(document.getElementById('ng-repeat-table-test'));
     console.log(elem.height());
  });
});