The idea is to load in new items to the top of a feed by pulling down
from the top of the list until you see a loading indicator, letting go,
and watching as new items magically (not really) add themselves in.
Ionic has an awesome directive that has undergone a redo fairly recently to accomplish exactly this.
Example
Next, we need to handle the pull to refresh. Recall we configured our directive to call a
In this function, we should call the
Ionic has an awesome directive that has undergone a redo fairly recently to accomplish exactly this.
ionRefresher (Pull to Refresh Directive)
The Ionic directive we are going to use is theion-refresher
The most basic usage is as follows:
<ion-refresher on-refresh="doRefresh()"></ion-refresher>
on-refresh
should point to a $scope
function
that gets the new data, updates a list, and then lets the refresher know
it is done. This refresher should be above some kind of list.Example
<ion-refresher on-refresh="doRefresh()"></ion-refresher>
<ion-list>
<ion-item class="item-avatar" ng-repeat="item in items">
<img src="{{item.user.picture.thumbnail}} " />
## {{item.user.name.first}} {{item.user.name.last}}
<p>{{item.user.location.city}} {{item.user.password}}</p>
</ion-item>
</ion-list>
Factory
In our example, we’re going to be making a call to the Random User API to get some data to play with. To do this, we’ll create a factory that makes these API calls. This factory will have two methods:GetFeed
and GetNewUser
. GetFeed
will be called when our app loads to get the initial data, and the GetNewUser
will be called each time we do a pull to refresh.
.factory('PersonService', function($http){
var BASE_URL = "http://api.randomuser.me/";
var items = [];
return {
GetFeed: function(){
return $http.get(BASE_URL+'?results=10').then(function(response){
items = response.data.results;
return items;
});
},
GetNewUser: function(){
return $http.get(BASE_URL).then(function(response){
items = response.data.results;
return items;
});
}
}
})
Controller
Our controller needs to do 2 things:- Fill the feed with the initial items
- Handle the pull to refresh
$scope.items
array.Next, we need to handle the pull to refresh. Recall we configured our directive to call a
doRefresh
function.In this function, we should call the
GetNewUser
function and add these items to the beginning of the array.
.controller('MyCtrl', function($scope, $timeout, PersonService) { $scope.items = []; PersonService.GetFeed().then(function(items){ $scope.items = items; }); $scope.doRefresh = function() { PersonService.GetNewUser().then(function(items){ $scope.items = items.concat($scope.items); //Stop the ion-refresher from spinning $scope.$broadcast('scroll.refreshComplete'); }); }; });
No comments:
Post a Comment