How to get correct element height and offset when using ng-repeat?

I am trying to get the offset and height of list items. After I have it, I call the function in the parent directive. In the end, these will be the elements of the transition to and from them when they appear.

Problem: Due to ng-repeat (I don’t know why) the values el[0].offsetheight and el[0].getBoundingClientRect().top; quite random; if, I don't wrap $timeout around the logic. I think this is because styles have time to render?

Question: how can I get the exact offset and height without wrapping $timeout or using $watch .

HTML:

 <dt spyed ng-repeat="exp in experiences"> ... </dt> 

JS:

 app.directive('spyed', function () { return { require: '^scrollSpyer', link: function(scope, el, attrs, ctrl) { // this value is mostly random after the $first ng-repeat item var offset = el[0].getBoundingClientRect().top; // this value is also mostly randome after the $first ng-repeat item var theHeight = el[0].offsetHeight; // this fires the expMapper on parent directive. ctrl.expMapper(offset, theHeight); } }; }); 

Explain why not use an observer: The reason I don't want to use an observer is because I return these values ​​to the collection in the parent directive. I don't want to flush the array, which I will need to do if it continues to fire ctrl.expMapper() with every 2way binding.

Parent Directive:

 app.directive('scrollSpyer', function ($window, Experiences) { return { controller: function($scope){ $scope.experiences = []; this.expMapper = function(offset, height) { $scope.experiences.push({'offset': offset, 'height': height, 'inView': false}); }; }, link: function(scope) { var i = 0; angular.element($window).bind('scroll', function() { if(i < scope.experiences.length) { if (this.pageYOffset >= scope.experiences[i].offset) { Experiences.status.push(scope.experiences[i]); i++; } else { console.log('middle'); } } scope.$apply(); }); } }; }); 
+6
source share
1 answer

Make it a function in $ scope:

 $scope.getOffsets = function () { //Do your logic here }; 

Pay attention to this small difference:

 <dt spyed ng-repeat="exp in experiences" ng-init="$last ? getOffsets(): ''"> ... </dt> 

ng-init, based on the condition of checking the last index, will do this without a timeout

0
source

Source: https://habr.com/ru/post/980019/


All Articles