June 27, 2016

How to add pull-to-refresh feature using Ionic Framework

To add a pull-to-refresh feature of an Ionic framework, we need to use ion-refresher element/component. On using this tag, when we pull down the screen it will invoke the js method we would like to execute. Add your logic in that method that you want to execute after this refresh trigger.

This is how you can write the refresher tag.

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

on-refresh executes the js method defined on page pull down. .
pulling-text displays the text while pulling down the page. 

Lets create one example to understand the use case of ion refresher. Lets create a plain page which on pull down refresh the page and will show 3 item list.

HTML Source Code:
 <!DOCTYPE html>  
 <html>  
  <head>  
   <meta charset="utf-8">  
   <title>MyApp</title>  
   <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">  
   <link href="css/ionic.css" rel="stylesheet">  
   <script src="js/ionic.bundle.js"></script>  
   <script src="js/app.js"></script>  
  </head>  
  <body ng-app="myApp">  
   <ion-pane>  
   <ion-header-bar class="bar-stable">  
    <h1 class="title">Number List</h1>  
   </ion-header-bar>  
   <ion-content ng-controller="THController">  
   <ion-refresher  
    pulling-text="Pull to refresh..."  
    on-refresh="doRefresh()">  
   </ion-refresher>  
   <ion-list>  
    <ion-item ng-repeat="item in nlist">  
     Number {{item}}   
    </ion-item>  
   </ion-list>  
   </ion-content>  
  </ion-pane>  
  </body>  
 </html>  

JavaScript Code (app.js):
 angular.module('myApp', ['ionic'])  
 .controller('THController', function($scope) {   
  $scope.doRefresh = function() {              
     $scope.nlist = [1,2,3];  
     $scope.$broadcast('scroll.refreshComplete');  
  };  
 });  

In above JS code, doRefresh method declared which initializes an array (nlist) of 3. On completion of this method it will displays the list on the page.

Screenshots of the example:

Before pull-to-refresh event trigger:


After event trigger:



No comments:

Post a Comment