× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Refreshing Items In Ionic Lists Ionic

Sasha
Aug 14, 2016
<p>With the rise of social networks, the “feed” has become a popular design pattern, especially in mobile apps. 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.</p> <p>Ionic has an&nbsp;<code>ionRefresher</code>&nbsp;directive that allows you to pull down from the top of the list and refresh the content.</p> <h3>DIRECTIONS</h3> <ol> <li> <p>Add the&nbsp;<code>&lt;ion-refresher&gt;</code>&nbsp;inside of the<code>&lt;ion-content&gt;</code>, before the&nbsp;<code>&lt;ion-list&gt;</code>:</p> <pre><code>&lt;ion-content ng-controller="AppCtrl"&gt; <span style="background-color:rgba(110, 226, 40, 0.298039)">&lt;ion-refresher pulling-text="Pull to refresh..." on-refresh="doRefresh()"&gt; &lt;/ion-refresher&gt;</span> &lt;ion-list&gt; </code></pre> <p><em>If you pull down from the top of the list, you will see "Pull to refresh...", followed by the refresher icon.</em></p> </li> <li> <p>In&nbsp;app.js, Add the&nbsp;doRefresh&nbsp;function to theAppCtrl&nbsp;controller, with an alert letting us know it's being called:</p> <pre><code>.controller('AppCtrl', function($scope) { <span style="background-color:rgba(110, 226, 40, 0.298039)">$scope.doRefresh = function() { alert("Refreshing"); };</span> </code></pre> </li> <li> <p>Notice that when you pull to refresh, the spinner doesn't go away. Add a broadcast after the alert in the&nbsp;doRefresh&nbsp;function, in order to tell the view that the refresh is complete:</p> <pre><code>$scope.doRefresh = function() { alert("Refreshing"); <span style="background-color:rgba(110, 226, 40, 0.298039)">$scope.$broadcast('scroll.refreshComplete');</span> }; </code></pre> </li> <li> <p>Modify the&nbsp;doRefresh&nbsp;function to add an item to the beginning of the list. Replace the alert with the following code:</p> <pre><code>$scope.doRefresh = function() { <span style="background-color:rgba(110, 226, 40, 0.298039)">// Subtract from the value of the first item ID to get the new one. var newId = $scope.items[0].id - 1; $scope.items.unshift({ id: newId });</span> $scope.$broadcast('scroll.refreshComplete'); }; </code></pre> <p><em>Now, every time you pull to refresh, a new item will be added to the beginning of the list. You can put whatever you would like in the&nbsp;<strong>doRefresh</strong>&nbsp;function. It is often used to make an API call that updates the list.</em></p> </li> </ol>