当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - How to get height of my ul element? In AngularJS without jQuery

问题描述:

Plnkr http://plnkr.co/edit/a7oV4gWzJG532RSqqOt3?p=preview

I'm building my own infinite scroll ability in an Angular project, and I need to obtain the height of my ul.

Currently I'm using this:

Markup

<ul id="tags-list">

<li ng-repeat="t in tags">

<div class="tag"

ng-mouseover="showTagDetails(t)"

ng-mouseleave="leaveTag(t)"

ng-click="sendTag(t)">{{t.name}}</div>

<tag-details tag="t"></tag-details>

</li>

</ul>

Controller

if ($scope.tags.length != 0 || $scope.tags.length != undefined) {

var theHeight = document.getElementById('tags-list').offsetHeight;

// var h = theHeight.style.height;

console.log(theHeight);

}

.offsetHeight is returning 0 for my ul for some reason.

var h = theHeight.style.height; did not return anything.

I do not want to use jQuery here to obtain the height, how would you do this?

网友答案:

Wrap the code inside your if statement with $timeout to give Angular the time it needs to change the DOM:

$timeout(function(){
  var theHeight = document.getElementById('tags-list').offsetHeight;
  console.log(theHeight);
});
网友答案:

The only way I was able to display the actual calulated height was to wait for Angular to re-render the DOM by forcing a timeout.

if ($scope.tags.length != 0 || $scope.tags.length != undefined) {
    var list= document.getElementById('tags-list');
    setTimeout(function(){
        console.log( list.offsetHeight );
    }, 100);
}

trevor's answer is better as it is an angular timeout service.

网友答案:

Working Plunker: http://plnkr.co/edit/RH1IBRVoowWFUoWvHGY8?p=preview

Wrap your code around a $timeout call. The DOM has not been yet being updated when your controller is initialized, that's why you need to wrap it with a $timeout.

$timeout(function() {
  if ($scope.tags.length != 0 || $scope.tags.length != undefined) {
    var theHeight = document.getElementById('tags-list').offsetHeight;
    // var h = theHeight.style.height;
    console.log(theHeight);
  }
});
分享给朋友:
您可能感兴趣的文章:
随机阅读: