Dai*_*Lew 6 javascript angularjs angularjs-directive
我正在尝试获取列表项的偏移量和高度.有了这些,我就在父指令上调用一个函数. 最后,当它们进入视图时,这将是过渡元素的输入和输出.
问题: 因为的ng-repeat(我不知道为什么),el[0].offsetheight和el[0].getBoundingClientRect().top;值是非常随机的; 除非,我$timeout绕过逻辑.我认为这是因为样式有时间渲染?
问题: 如何获得精确的偏移量和高度,无需包裹$timeout或使用$watch.
HTML:
<dt spyed ng-repeat="exp in experiences">
...
</dt>
Run Code Online (Sandbox Code Playgroud)
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);
}
};
});
Run Code Online (Sandbox Code Playgroud)
关于为何不使用观察者的旁注:
我不想使用观察者的原因是我将这些值推送到父指令中的集合.我不想继续重置数组,如果它继续触发ctrl.expMapper()每个2way绑定,我将不得不这样做.
家长指令:
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();
});
}
};
});
Run Code Online (Sandbox Code Playgroud)
使其成为 $scope 中的函数:
$scope.getOffsets = function () {
//Do your logic here
};
Run Code Online (Sandbox Code Playgroud)
请注意这个微小的差异:
<dt spyed ng-repeat="exp in experiences" ng-init="$last ? getOffsets(): ''">
...
</dt>
Run Code Online (Sandbox Code Playgroud)
ng-init 基于条件检查最后一个索引将使得这种情况发生而不会超时