[英]Ionic / Angular - Refresh articles on app resume
I have developed a News App using Ionic / Angular. 我已经使用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. $scope.articles = articles
从外部JSON文件读取文章。
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?
有人可以帮助我实现这一目标吗?
A good solution is using the cordova resume
event and fire your refresh callback when it gets triggered. 一个好的解决方案是使用cordova
resume
事件,并在触发它时触发刷新回调。 You can define this by using the following code: 您可以使用以下代码进行定义:
document.addEventListener("resume", yourCallbackFunction, false);
However, a better approach is to use the $ionicPlatform
service. 但是,更好的方法是使用
$ionicPlatform
服务。
.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');
};
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.