javascript - ngInfiniteScroll 被调用的次数超出了其需要的次数

标签 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;
                }
            });
    }

数据库每次查询时的获取限制为“10”,并接受偏移量。我有一个包含 11 个帖子的数据集,只是为了测试。如果它有效,它应该在页面加载时加载前 10 个,并在我滚动时立即加载第 11 个。虽然这在某些时候有效,但大多数时候都会崩溃。我所说的破坏是指它加载最后一篇文章 3-4 次。我通过每次调用该函数时记录 $scope.posts.length 来测试它。页面加载时,长度为 10,但当我向下滚动时,它会多次添加最后一个元素。任何帮助都会很棒!

最佳答案

问题是,你启动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
        });
}

关于javascript - ngInfiniteScroll 被调用的次数超出了其需要的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23209265/

相关文章:

javascript - 使用不记名 token 在 JavaScript 中加载图像

javascript - Angular.js 仅加载一半时间

javascript - 在 Angular 1.3 中将对象注入(inject)到嵌入内容的范围中

javascript - 以下 angularJS 声明属于哪个命名空间?

javascript - ng-bind-html 和 ng-controller

javascript - 更新 api 调用 React 中的设置状态

javascript - FullScreenChange 事件不起作用

javascript - 为什么在 Benchmark.js 中设置、拆卸和循环的目的是?

javascript - JavaScript 中的第 n 个子级选择器

angularjs - $httpBackend.whenGET 多参数