Wednesday, August 3, 2016

Infinite Scroll

Add ‘infinite scroll’ and ‘pull to refresh’ function
overcome limitation of getting fixed number of stories.
no way to display newer stories or older stories back in time

what is ‘infinite scroll’ and ‘pull to refresh’ ?

From https://www.reddit.com/dev/api

“Listings do not use page numbers because their content changes so frequently. Instead, they allow you to view slices of the underlying data. Listing JSON responses contain after and before fields which are equivalent to the "next" and "prev" buttons on the site and in combination with count can be used to page through the listing.”

before - new stories
after - older stories

Install JSONView from Chrome web store if you have not to view JSON files formatted

name: "t3_4w1ws2",
https://www.reddit.com/r/Android/new/.json?before=t3_4w1ws2

http://ionicframework.com/docs/api/directive/ionInfiniteScroll/

<ion-content ng-controller="MyController">
  <ion-list>
  ....
  ....
  </ion-list>

  <ion-infinite-scroll
    on-infinite="loadMore()"
    distance="1%">
  </ion-infinite-scroll>
</ion-content>

index.html

<ion-content>      
  <div class="list">            
    <a class="item item-thumbnail-left" ng-repeat="story in stories track by story.id" href="{{story.url}" target="_blank">
      <img ng-src="{{story.thumbnail}}" ng-if="story.thumbnail.indexOf('http') === 0">
      <h2 class="story-title">{{story.title}}</h2>
      <p>
        <span am-time-ago="story.created_utc" am-preprocess="unix"></span>     
        -
        {{story.domain}}
      </p>
    </a>          
  </div>
  <ion-infinite-scroll
    on-infinite="loadOlderStories()"
    distance="1%">
  </ion-infinite-scroll>        
</ion-content>

app.js

(function(){

var app = angular.module('myreddit', ['ionic','angularMoment']);

app.controller('RedditCtrl',function($http,$scope){
  
  $scope.stories = [];

  $scope.loadOlderStories = function(){
    var params = [];
    if($scope.stories.length > 0){
      params['after'] = $scope.stories[$scope.stories.length - 1].name;
    }    
    $http.get('https://www.reddit.com/r/Android/new/.json', {params: params})
      .success(function(response){
        angular.forEach(response.data.children,function(child){
          $scope.stories.push(child.data);
        });
        $scope.$broadcast('scroll.infiniteScrollComplete');
      });
  };

});

Trying scrolling. It should pump in more data as you scroll.

No comments:

Post a Comment