我正在尝试进行反向无限滚动。我有一个评论列表,其中我接收到最近的10条评论,并希望用户能够向上滚动以检索下一个10条-类似于FB,它显示最新的评论与“获取前一个”链接,而不是链接通过滚动事件。
注意:在示例中,我通过在滚动事件中保存顶部li并调用scrollIntoView()直到我添加模拟ajax调用的超时,使其正常工作。有了超时,请求回来之前顶部li就会滚动到视图中,并且新元素被呈现出来 :/
我从http://jsfiddle.net/vojtajina/U7Bz9/开始,并尝试将其修改为反向无限滚动,很快就得到了这样的结果:
function Main($scope, $timeout) {
$scope.items = [];
var counter = 0;
$scope.loadMore = function() {
// simulate an ajax request
$timeout( function() {
for (var i = 0; i < 5; i++) {
$scope.items.unshift({id: counter});
counter += 10;
}}, 1000);
};
$scope.loadMore();
}
angular.module('scroll', []).directive('whenScrolled', ['$timeout', function($timeout) {
return function(scope, elm, attr) {
var raw = elm[0];
$timeout(function() {
raw.scrollTop = raw.scrollHeight;
}, 1100);
elm.bind('scroll', function() {
// note: if test for < 100 get into infinite loop due to
// the delayed render
if (raw.scrollTop === 0) {
var sh = raw.scrollHeight
scope.$apply(attr.whenScrolled);
// the items are not loaded and rendered yet, so
// this math doesn't work
raw.scrollTop = raw.scrollHeight - sh;
}
});
};
}]);
http://jsfiddle.net/digger69/FwWqb/2/
问题在于,当获取下一批10个项目时,它们被添加到列表顶部并且整个列表重新渲染,处于列表末尾的项目完全滚出视图。在示例中,项目“40”位于顶部,当您向下滚动并向上滚动以触发滚动时,“90”项目将位于顶部。我正在寻找一种良好的策略,在呈现后将“40”保持在滚动区域的顶部。注意:在示例中,我通过在滚动事件中保存顶部li并调用scrollIntoView()直到我添加模拟ajax调用的超时,使其正常工作。有了超时,请求回来之前顶部li就会滚动到视图中,并且新元素被呈现出来 :/
var top = elm.find("li")[0];
scope.$apply(attr.whenScrolled);
top.scrollIntoView();