如何在使用 ng-repeat(ng-repeat)时获取元素的正确高度和偏移值

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

本文关键字:ng-repeat 高度 元素 获取      更新时间:2023-09-26

我正在尝试获取列表项的偏移量和高度。一旦我有了这些,我就会在父指令上调用一个函数。 最后,这将是进入和退出的过渡元素,当它们进入视野时。

问题:由于ng-repeat(我不知道为什么(,el[0].offsetheightel[0].getBoundingClientRect().top;值几乎是随机的;除非,我围绕逻辑进行$timeout我认为这是因为样式有时间渲染?

问题:如何在没有包装$timeout或使用$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);
        }
    };
});

关于为什么不使用观察程序的旁注:我不想使用观察程序的原因是我将这些值推送到父指令中的集合。 我不想继续重置数组,如果它在每个 2way 绑定上不断触发ctrl.expMapper(),我将不得不这样做。

家长指令:

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();
            });
        }
    };
});

让它成为$scope函数:

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

请注意这个微小的差异:

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

ng-init 基于检查最后一个索引的条件将使这种情况在没有超时的情况下发生