正在调用的ngInfiniteScroll超出了它的需要

时间:2014-04-22 02:20:46

标签: javascript angularjs angularjs-directive angularjs-ng-repeat nginfinitescroll

我有以下使用ngInfiniteScroll的无序列表:

<ul class="list-group" infinite-scroll="loadMore()">

<li ng-repeat="post in posts | filter:search" class="list-group-item isteacher-{{post.isteacher}}"><a href="/post/{{post.postid}}"><h4>{{post.title}}</h4></a> by <a href="/author/{{post.authorid}}">{{post.author}}</a> on <small>{{post.date}}</small></li>
</br>

</ul>

我的loadMore()函数使用偏移量查询数据库。偏移量是到目前为止加载的项目数。我已经手动测试了它并且工作正常。

    $scope.offset = 0;
    $scope.posts = [];
    $scope.loadMore = function(){
        $http.get('/getposts?offset='+$scope.offset)
            .success(function(data){
                var newList = data.post_list;
                if(newList.length>0){
                    for(var x=0; x<newList.length; x++){
                        $scope.posts.push(newList[x]);
                    }
                    $scope.offset+=newList.length;
                }
            });
    }

数据库的获取限制为&#34; 10&#34;每次查询,并接受偏移。我有一个11个帖子的数据集,只是为了测试。如果它工作,它应该在页面加载时加载前10个,并在我滚动时加载第11个。虽然这在某些时候有效,但它在大部分时间都会中断。我打破它的意思是它加载最后一个帖子3-4次。我每次调用函数时都会通过记录$scope.posts.length来测试它。当页面加载时,长度为10,但是当我向下滚动时,它会多次添加最后一个元素。任何帮助都会很棒!

1 个答案:

答案 0 :(得分:8)

问题是,您启动http get请求并等待响应。与此同时,您正在向上滚动并完成,您的功能将再次被调用。这可能是为什么最后一个帖子被多次加载的原因。但是,如果查询成功,则将newList.length添加到偏移量中。解决此问题的可能方法:

$scope.offset = 0;
$scope.posts = [];
$scope.isBusy = false;
$scope.loadMore = function(){
    if($scope.isBusy === true) return; // request in progress, return
    $scope.isBusy = true;
    $http.get('/getposts?offset='+$scope.offset)
        .success(function(data){
            var newList = data.post_list;
            if(newList.length>0){
                for(var x=0; x<newList.length; x++){
                    $scope.posts.push(newList[x]);
                }
                $scope.offset+=newList.length;
            }
            $scope.isBusy = false; // request processed
        });
}
相关问题