如何留住在AngularJS NG重复的滚动位置? [英] How to retain scroll position of ng-repeat in AngularJS?
问题描述
对象的列表是使用渲染 NG-重复
。假设这个名单很长,而且用户滚动至底部看到一些对象。
List of objects is rendered using ng-repeat
. Suppose that this list is very long and user is scrolling to the bottom to see some objects.
虽然用户正在观察的对象,新项目被添加到该列表的顶部。这使得观察对象,以改变其立场,即用户突然看到别的东西在同一个地方被观察对象的。
While user is observing an object, a new item is added to the top of the list. This causes the observed object to change its position, i.e. the user suddenly sees something else at the same place of the observed object.
您会如何去当增加新的项目保持观察对象在同一个地方?
How would you go about keeping the observed object at the same place when new items are added?
推荐答案
这也许解决了相当漂亮,使用的
。我用了两个指令 - 手柄之一滚动包装元素的位置,其他注册新的元素。 scrollTop的
属性的div
如果给我一个喊什么不清楚的地方。
It maybe solved quite elegantly, by using scrollTop
property of div
. I used two directives - one handles scroll position of the wrapper element, the other register new elements.
Give me a shout if anything unclear.
JS:
.directive("keepScroll", function(){
return {
controller : function($scope){
var element = null;
this.setElement = function(el){
element = el;
}
this.addItem = function(item){
console.log("Adding item", item, item.clientHeight);
element.scrollTop = (element.scrollTop+item.clientHeight+1);
//1px for margin from your css (surely it would be possible
// to make it more generic, rather then hard-coding the value)
};
},
link : function(scope,el,attr, ctrl) {
ctrl.setElement(el[0]);
}
};
})
.directive("scrollItem", function(){
return{
require : "^keepScroll",
link : function(scope, el, att, scrCtrl){
scrCtrl.addItem(el[0]);
}
}
})
HTML
<div class="wrapper" keep-scroll>
<div class="item" scroll-item ng-repeat="item in items | orderBy: '-id'">
{{ item.name }}
</div>
</div>
这篇关于如何留住在AngularJS NG重复的滚动位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!