简体   繁体   中英

Can't calculate offsetHeight from an element in AngularJS

I've got the following directive:

app.directive('myObject', function(){
  return {
    restrict: 'A',
    link: function(scope, elem){
      console.log(elem[0].offsetHeight);
    }
  };
});

Which basically is logging the offsetHeight of its target element, but it isn't working. I guess its because its calculating the height when the element hasn't got any content yet.

How can I resolve this issue without using a timeout ? Is there any built in solution for this problem?

Plunkr

The problem is ng-repeat renders lazily and the link function gets fired before that. You could resolve this issue by having watcher which will evaluate elem[0].offsetHeight value on each digest cycle. Therefore when ng-repeat completes it rendering it calls a digest cycle and due to change in elem[0].offsetHeight value it call its callback.

Directive

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

app.directive('myObject', function(){
  return {
    restrict: 'A',
    link: function(scope, elem){
      var calculateHeight = scope.$watch(function(){
        return elem[0].offsetHeight;
      }, function(newVal, oldVal){
        //my awesome code here.
        console.log(newVal, oldVal);
        calculateHeight(); //de-registering watcher for performance reason
      })
    }
  };
});

Demo Here


Other alternative way you can do is, you can place other directive on ng-repeat element which will $emit an event once it completes with rendering & then we will have event listener inside directive, which will listen out that event and calculate height.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM