angularjs - JSON Response with infinite scroll -
i have troubles infinite scroll function. every time when scroll down loadmore function called twice , every time load 2 page instead of 1 page. in log see loading 2 , 3 page:
loadmore 2 loadmore 3
then load 4 , 5 page:
loadmore 4 loadmore 5
this controller:
.controller('postsctrl', function( $scope, $http, dataloader, $timeout, $ionicslideboxdelegate, $rootscope, $log ) { var postsapi = $rootscope.url + 'posts'; $scope.moreitems = false; $scope.loadposts = function() { // of our posts dataloader.get( postsapi ).then(function(response) { $scope.posts = response.data; $scope.moreitems = true; $log.log(postsapi, response.data); }, function(response) { $log.log(postsapi, response.data); }); } // load posts on page load $scope.loadposts(); paged = 2; // load more (infinite scroll) $scope.loadmore = function() { if( !$scope.moreitems ) { return; } var pg = paged++; $log.log('loadmore ' + pg ); $timeout(function() { dataloader.get( postsapi + '?page=' + pg ).then(function(response) { angular.foreach( response.data, function( value, key ) { $scope.posts.push(value); }); if( response.data.length <= 0 ) { $scope.moreitems = false; } }, function(response) { $scope.moreitems = false; $log.error(response); }); $scope.$broadcast('scroll.infinitescrollcomplete'); $scope.$broadcast('scroll.resize'); }, 1000); } $scope.moredataexists = function() { return $scope.moreitems; } // pull refresh $scope.dorefresh = function() { $timeout( function() { $scope.loadposts(); //stop ion-refresher spinning $scope.$broadcast('scroll.refreshcomplete'); }, 1000); }; })
how call loadmore 1 time? template:
<ion-view view-title="posts"> <ion-content> <ion-refresher on-refresh="dorefresh()"></ion-refresher> <ion-list> <ion-item class="item-icon-right" ng-repeat="post in posts track $index" href="#/app/posts/{{post.id}}" track> <!-- <img ng-if="post.featured_image" ng-src="{{post._embedded['http://v2.wp-api.org/attachment'][0][$index].source_url}}" class="alignleft" /> --> <h2 ng-bind-html="post.title.rendered"></h2> <p ng-if="post.excerpt.rendered" ng-bind-html="post.excerpt.rendered"></p> <i class="icon ion-chevron-right icon-accessory"></i> </ion-item> </ion-list> <ion-infinite-scroll ng-if="moredataexists()" on-infinite="loadmore()" distance="1%" immediate-check="false"> </ion-infinite-scroll> </ion-content> </ion-view>
you should broadcast infinitescrollcomplete event inside callback of dataloader.get
what's happenning method assincronous, data being added list after event fired.
try changing code this, , should work.
dataloader.get( postsapi + '?page=' + pg ).then(function(response) { angular.foreach( response.data, function( value, key ) { $scope.posts.push(value); }); if( response.data.length <= 0 ) { $scope.moreitems = false; } // place here $scope.$broadcast('scroll.infinitescrollcomplete'); }, function(response) { $scope.moreitems = false; $log.error(response); });
Comments
Post a Comment