Вопрос

I have the following unordered list that uses 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>

My loadMore() function queries the database with the offset. The offset being the number of items that are loaded thus far. I've tested this by hand and it works fine.

    $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;
                }
            });
    }

The database has a fetch limit of "10" everytime it is queried, and accepts an offset. I have a dataset of 11 posts, just to test. If it works, it should load the first 10 when the page loads, and the 11th one as soon as I scroll. While this works some of the time, it breaks most of the time. What I mean by it breaking is that it loads the last post 3-4 times. I tested it by logging $scope.posts.length every time the function is called. When the page loads, the length is 10, but as I scroll down it keeps adding the last element multiple times. Any help would be great!

Это было полезно?

Решение

The problem is, you start the http get request and waiting for the response. Meanwhile you are scrolling up and done and your function would be called again. That could be the reason why the last posts are loaded multiple times. However, and if the query was successful than you are adding newList.length to your offset. Possible solution for this problem:

$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
        });
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top