简体   繁体   中英

Angularjs how to stop infinity scroll when server has no more data to send

Based on THIS example which I have modified with an Ajax request to get the data Im struggling to find a way to stop it when the server has no more data to send.

I have tried to add a boolean variable in a service , and a $watch method in the directive but it is not working.

Is there a simple way to to achieve that ?

This is not my code but if there is no easy answer I can post my code with the changes I have done.

thanks for your help.

<div id="fixed" when-scrolled="loadMore()">
  <ul>
    <li ng-repeat="i in items">{{i.id}}</li>
  </ul>  
</div>

function Main($scope) {
    $scope.data = { comments : [] }
    $scope.loadMore =  function(){
        $http({
            url: '/comment/next',
            method: "POST"
        })
        .success(function(data){
            for(var i=0; i<data.length; i++){
                $scope.data.comments.push(data[i]);
            }        
        });
    }
}

angular.module('scroll', []).directive('whenScrolled', function() {
    return function(scope, elm, attr) {
        var raw = elm[0];

        elm.bind('scroll', function() {
            if (raw.scrollTop + raw.offsetHeight >= raw.scrollHeight) {
                scope.$apply(attr.whenScrolled);
            }
        });
    };
});

I can only guess as to a solution without seeing more of your code (specifically what is returned by $http results), but I believe this sort of thing could work, depending on the structure of a comment object.

function Main($scope) {
    $scope.data = { comments : [] }
    $scope.scrollComplete = false;
    $scope.loadMore =  function(){            
        if($scope.scrollComplete || $scope.loading) { return; }
        $scope.loading = true;
        $http({
            url: '/comment/next',
            method: "POST"
        })
        .success(function(data){
            for(var i=0; i<data.length; i++){
                var totalComments = $scope.data.comments.length;
                if($scope.data.comments[totalComments - 1].someID === data[i].someID){
                    $scope.scrollComplete = true;
                }else{
                    $scope.data.comments.push(data[i]);
                }
            } 
            $scope.loading = false;       
        }).error(function(){ $scope.loading = false });
    }
}

Just bear in mind that a solution like this isn't really elegant. What I like to do is allow an item ID to be passed to the API (ie your /comment/next), and treat that as the last grabbed item. So the API will only give me back everything after that. Using that method, you would simply have to pass the last comment ID to the API.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM