Andrei Andrei - 1 month ago 12
AngularJS Question

Ionic / Angular - Refresh articles on app resume

I have developed a News App using Ionic / Angular. Here is the code for the News Tab:

<ion-view view-title="News">
<ion-content class="padding">
<ion-refresher pulling-text="Actualizeaz─â articolele" on-refresh="doRefresh()">
</ion-refresher>
<a class="article" ng-repeat="article in articles" href="#/tab/news/{{article.id}}">
<img ng-src="{{article.image}}" class="article-image">
<h2 class="article-title">{{article.title}}</h2>
<p class="article-published">{{article.published}}</p>
<p class="article-intro">{{article.intro}}...</p>
</a>
</ion-content>
</ion-view>


And here is the controller:

.controller('NewsCtrl', function($scope, Articles) {
Articles.all().then(function(articles) {
$scope.articles = articles
});
$scope.doRefresh = function() {
Articles.all().then(function(articles) {
$scope.articles = articles
});
$scope.$broadcast('scroll.refreshComplete');
};
})


$scope.articles = articles
reads the articles from an external JSON file.

So I have the pull to refresh option working but there is one problem. If a user keeps the app open in the background I would like the articles to be refreshed when the user opens the app again. Someone can help me achieve this?

Answer

A good solution is using the cordova resume event and fire your refresh callback when it gets triggered. You can define this by using the following code:

document.addEventListener("resume", yourCallbackFunction, false);

However, a better approach is to use the $ionicPlatform service.

.controller('NewsCtrl', function($scope, Articles, $ionicPlatform) {

  $ionicPlatform.on('resume', $scope.doRefresh);

  Articles.all().then(function(articles) {
    $scope.articles = articles
  });

  $scope.doRefresh = function() {
    Articles.all().then(function(articles) {
      $scope.articles = articles
    });
    $scope.$broadcast('scroll.refreshComplete');
  };

})

Also, another approach is to broadcast on the root scope to avoid breaking the angular way inside a controller.

app.module('myApp',[])
    .run(function ($rootScope) {

        document.addEventListener("resume", function () {        
            $rootScope.$broadcast('onAppResume');        
        }, false);        
    });

Then you can listen to this event from your controllers:

.controller('NewsCtrl', function($scope, Articles) {

  $scope.$on('onAppResume', $scope.doRefresh);

  Articles.all().then(function(articles) {
    $scope.articles = articles
  });

  $scope.doRefresh = function() {
    Articles.all().then(function(articles) {
      $scope.articles = articles
    });
    $scope.$broadcast('scroll.refreshComplete');
  };

})
Comments