Ionic - Reload and display new data in ng-repeat when clicking back button

Chad picture Chad · Mar 9, 2015 · Viewed 19.7k times · Source

Background

I have an ng-repeat list that goes to a details page (which has a back button). The $scope.items variable is loaded from a get request that occurs when the page is first loaded, with my refreshItems() function.

The Problem

When you click the back button on the details page, you are taken back to the correct page, but the list is not refreshed. I need this list to refresh so the new items are loaded and shown.

Attempted Solution

I thought that I could simply hook up the Back button to an ng-click function that uses ionicHistory to go back, and then calls my refreshItems() function; however, this does not reload the items on the first page.

The above attempt does go back to the last page and trigger the refreshItems() function (and the new data is loaded, which I can see thanks to console.log() statements), but I'm guessing the ng-repeat needs to be rebuilt. I found some information on $scope.$apply() as well as $route.reload() but neither of these fixed the problem when I placed them at the end of my goBack() function.

Code Excerpts

controller.js

$scope.refreshItems = function() {

    console.log("Refreshing items!");

    $http.get('http://domain/page.aspx').then(function(resp) {
        $scope.items = resp.data; console.log('[Items] Success', resp.data);
    }, function(err) { console.error('ERR', err); });

};


$scope.goBack = function() {
    $ionicHistory.goBack();
    $scope.refreshItems();
};

Main Page HTML

<div class="list">

    <a ng-repeat="i in items" class="item" href="#/tab/details?ID={{i.Item_ID}}">
        <b>Item {{i.Item_Name}}</b>
    </a>

</div>

Back Button on Details Page

<ion-nav-bar>
    <ion-nav-back-button class="button-clear" ng-click="goBack();">
        <i class="ion-arrow-left-c"></i> Back
    </ion-nav-back-button>
</ion-nav-bar>

Possible Direction?

I have a refresher on the main page which calls refreshItems() - and it refreshes them correctly. The problem is most certainly when I try to pair refreshing with either $ionicHistory.goBack() or $state.go(). Is there a way I can programmatically call the refresher (after/on load), since directly calling the function that refresher is calling is not working?

Answer

9nix00 picture 9nix00 · Apr 11, 2015

Set the cache flag in ionicConfigProvider. Disable cache within state provider as follows:

$stateProvider.state('mainPage', {
   cache: false,
   url : '/dashboard',
   templateUrl : 'dashboard.html'
})

See the manual for details.