Like native Android apps, we sometimes need a view, where list items can be loaded after user reached the bottom of all loaded list items. This behavior is recommended if we have a long list to load and we don’t want the user to tap next every time to view next set of list items.
So we will do basically two things:
-
How to Check If User Reached Bottom of Page/ View in Ionic App?
-
How to Auto Load Infinite List of Records from API call in Single Ionic View?
Let’s begin…
Step 1) – In Our controller, we need to add an Ionic service $ionicScrollDelegate, then our controller will look something like this
...
.controller('WallCtrl', function($scope, $ionicScrollDelegate) {
})
...
Step 2) – Now we need to add some events in HTML which will call our Scroll function from the controller.
We will add on-scroll-complete=”checkScroll()” on our content HTML like below:
NOTE: I have used on-scroll-complete event Instead on on-scroll, becouse if we use on-scroll it will file on every pixel movement which can call api multiple times
<ion-view view-title="Wall">
<ion-content on-scroll-complete="checkScroll()">
<div class="list" ng-repeat="w in data.wallList">
</div>
</ion-content>
</ion-view>
Step 3) – In the controller, we will write logic to check if the view reached the bottom.
$scope.checkScroll = function() {
var currentTop = $ionicScrollDelegate.getScrollPosition().top;
var maxTop = $ionicScrollDelegate.getScrollView().__maxScrollTop;
if (currentTop >= maxTop) {
// hit the bottom
// Call API to Load Data
$scope.loadNextRecords();
}
};
In above function $scope.loadNextRecords() will call more records and push to existing list.
Sometimes this we may want to call loadNext immediately when the user reaches the middle of the list, for that we can adjust values of currentTop and maxTop accordingly.
Check Demo link, check console.log on link
Let me know if you have any feedback issues of better suggestion in comments below 🙂
Leave a Reply