Infinite scroll

Hi,
i’m trying to get my infinite scroll to work. How would i do this?
I’d like my application to load 5 json messages in to start with and then when the user scrolls downwards it would continue to load more messages.

What i’ve got at the moment is a pull to refresh which loads details from a Json webpage. I’d like it to only load the newest messages first but when it scrolls downwards it would load the other messages. Hope that make sense.

Here’s my code:

HTML

    <ion-refresher 
        pulling-text="Pull to refresh..."
        on-refresh="doRefresh()">
    </ion-refresher>

    <ion-list>
        <ion-item ng-repeat="data in data">
            <div class="list card">
                <div class="item item-divider">{{data.announcement_name}} - {{data.date}}</div>
                <div class="item item-body">
                    <div>
                        {{data.message}}
                    </div>
                </div>
            </div>
        </ion-item>
    </ion-list>
    <ion-infinite-scroll></ion-infinite-scroll>

</ion-content>

Javascript controller

angular.module('starter.controllers', [])

.controller('announcementsCtrl', function($scope, $http) {
    $scope.data = [];
    $scope.doRefresh = function () {
    $http.get('http://wikicode.co.uk/announcement.json')
        .success(function (data) {
            $scope.data = data;
        })
        .finally(function () {
            $scope.$broadcast('scroll.refreshComplete');
        });
    }
    $scope.loadMore = function() {
    console.log('Loading more!');
    

      $scope.$broadcast('scroll.infiniteScrollComplete');
      $scope.$broadcast('scroll.resize');
      $scope.$broadcast('scroll.resize')
    }, 1000;
  })

If someone could help me or point me in the right direction that would be brilliant!

I’m not sure exactly what you mean. If you’re trying to load all of the data at the beginning but only show some of it until the user scrolls, you can use limitTo. Here is an example Codepen where it loads the data in one at a time as they scroll down:

Let me know if I misunderstood you. Also, the hard coded data in the $http.error is because of CORS issues in the Codepen.

2 Likes

Thanks brandy, that’s exactly what i wanted! Thanks.

When i pull down to refresh the list disappears and gets re-loaded again. Is there a way to stop it deleting the data but instead just load new data if it finds any, when i pull down to refresh? Hope that makes sense.

You can remove the limit reset in the success/error function: $scope.infiniteLimit = 1;

That will make it so if you have all 5 showing they will still be showing but when new data is pulled in it will only show the first 5 of the new data.

2 Likes

Fantastic!! Thank you

2 Likes

Dear Brandy Shea, thanks to your post I successfully managed to implement refresh and scroll functions. Fantastic, thanks again.