1

我有一个使用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,但是当我向下滚动时,它会多次添加最后一个元素。任何帮助将是伟大的!

回答

7

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

非常感谢!他们在[Reddit演示](http://sroze.github.io/ngInfiniteScroll/demo_async.html)中执行此操作,推测我认为这是特定于该示例的。我会尽快接受答案。 – user2200321

+0

@Eugen Meissner - 任何想法为什么可以在每次滚动时调用loadMore()函数?像它不计算正确的父母身高? – neoswf

+0

我已经使用这个答案,它的工作原理,但数据来无穷,不停止是什么原因@Euregano –