如何在使用 ng-repeat(ng-repeat)时获取元素的正确高度和偏移值
How to get correct height and offset values of an element when using ng-repeat?
我正在尝试获取列表项的偏移量和高度。一旦我有了这些,我就会在父指令上调用一个函数。 最后,这将是进入和退出的过渡元素,当它们进入视野时。
问题:由于ng-repeat
(我不知道为什么(,el[0].offsetheight
和el[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 基于检查最后一个索引的条件将使这种情况在没有超时的情况下发生
相关文章:
- ng init中的表达式无法使用ng repeat
- Angular ng repeat order将多个字段作为一个字段
- 访问ng repeat中的第一个项目
- Angular js+ng repeat+字母数字索引不起作用
- 如何正确应用Angularjs ng repeat
- AngularJS Navigation (li ng-repeat, create header li), DOM
- 如何使用ng repeat中的选定输入更新我的对象
- 无法使用ng repeat检索动态创建的JSON对象的属性
- 使用 ng-repeat访问 ng 表单元素/值
- Toggle Switch在包含ng model和ng repeat之后不进行切换
- 如何在ng repeat angular js中使用$index
- 在Angularjs中,我如何使用ng repeat、ng model和ng click来动态更改内容
- ng repeat在ng repeat-过滤器不工作
- 在ng repeat中使用带有orderBy的方法
- Angular JS ng-repeat
- 在ng repeat中使ng disabled为true
- AngularJS:如何在ng repeat中使用$index
- 复选框无法正常使用ng repeat,AngularJs
- 如何避免在HTML中使用ng repeat对url名称进行硬编码
- 如何在使用 ng-repeat(ng-repeat)时获取元素的正确高度和偏移值