a blog for those who code

Sunday 20 March 2016

Repeater Control in Ionic Framework with Refresh

In this post we will be discussing about repeater control in Ionic Framework with refresh option. There are lot of scenario where you fetch the data from the API and the data gets updated frequently. Now in this case you want your user to see the updated value when they refresh the page. So in this post we will show you how you can show your data to the user in the repeater control and how to refresh them.

The Ionic Framework has a collection-repeat directive that you can use instead of ng-repeat because collection-repeat allows an app to show huge lists of items with great performance than ng-repeat.

At first we will update our index.html to the below code :

<body ng-app="starter">
  <ion-nav-bar class="bar-stable"></ion-nav-bar>
  <ion-nav-view></ion-nav-view>
</body>

Next we will write our Controller i.e. repeaterCtrl which will give us the data

.controller('repeaterCtrl', function ($scope) {
  $scope.values = [];
  for(i=0;i<10;i++)
  {
    var value = {
      randomNumber: Math.random(),
      date: new Date().toLocaleDateString()
    }
    $scope.values.push(value);
  }

  $scope.doRefresh = function () {
    $scope.values = [];
    for (i = 0; i < 10; i++) {
      var value = {
        randomNumber: Math.random(),
        date: new Date().toLocaleDateString()
      }
      $scope.values.push(value);
    }
    $scope.$broadcast('scroll.refreshComplete');
  }
})

In the above code we are creating our items array and then inserting 10 random values, we can even fetch data from the API. Next we are writing a function which will again call the API to get the updated values. After updating the values we will do a broadcast to notify that the refresh is complete.

Next we will write our page1.html which is created inside templates folder as shown below

<ion-view view-title="Repeater Controller Example (Pull to Refresh)">
  <ion-content class="padding">
    <ion-refresher pulling-text="Update Date" on-refresh="doRefresh()"></ion-refresher>
    <ion-list>
      <ion-item collection-repeat="value in values">
        <p>Random Value : {{value.randomNumber}}</p>
        <p>Date : {{value.date}}</p>
      </ion-item>
    </ion-list>
  </ion-content>
</ion-view>

In the above code we are creating a list using ion-list with each item added in a ion-item using collection-repeat directive. We are also using ion-refresher which will call the doRefresh() function on refreshing.

Our app.js file will have the code as shown below were we are configuring the state.

.config(function($stateProvider, $urlRouterProvider) {
  .state('page1', {
    url: "/page1",
    templateUrl: 'templates/page1.html',
    controller: 'repeaterCtrl'
  })

  $urlRouterProvider.otherwise('/page1');
}); 

After running you will get the following output :




Please Like and Share the CodingDefined.com Blog, if you find it interesting and helpful.

No comments:

Post a Comment