Reputation: 51
I want my app automatically refresh to retrieve latest data from API whenever user press the notification sent by onesignal pushnotification server. Below is my sample code, I having trouble to call controller function to dorefresh() from App.js. Or is there any other workaround can let me retrieve latest data?
App.js
angular.module('starter', ['ionic','starter.controllers'])
.run(function($ionicPlatform, $rootScope) {
$ionicPlatform.ready(function() {
// Enable to debug issues.
// window.plugins.OneSignal.setLogLevel({logLevel: 4, visualLevel: 4});
var notificationOpenedCallback = function(jsonData) {
//alert("Notification received:\n" + JSON.stringify(jsonData));
//console.log('didReceiveRemoteNotificationCallBack: ' + JSON.stringify(jsonData));
$rootScope.openedFromNotification = true;
alert($rootScope.openedFromNotification);
$ionicHistory.clearCache();
$window.location.reload(true);
};
// Update with your OneSignal AppId and googleProjectNumber before running.
window.plugins.OneSignal.init("xxxxxxxxxxxxxxxx",
{googleProjectNumber: "xxxxxxxxxxxxxx"},
notificationOpenedCallback);
});
})
Controller.js
angular.module('starter.controllers',['ionic'])
.controller('MainCtrl', function($scope, $rootScope, $http) {
$http.get("localhost/test/getitem.php")
.success(function (response)
{
$scope.items = response;
});
$scope.doRefresh = function() {
console.log("Refreshing!");
$http.get("localhost/test/getitem.php")
.success(function(response) {
$scope.items = formatData(response);
})
.finally(function() {
$scope.$broadcast('scroll.refreshComplete')
})
};
Index.html
<ion-refresher pulling-text="Pull to refresh" on-refresh="doRefresh()">
</ion-refresher>
<div class="item">
<h2 style="text-align:center; font-size:25px; font-weight:">{{item.name}}</h2>
</div>
Upvotes: 4
Views: 2530
Reputation: 35587
You can broadcast an event in the notificationOpenedCallback
:
var notificationOpenedCallback = function(jsonData) {
//alert("Notification received:\n" + JSON.stringify(jsonData));
//console.log('didReceiveRemoteNotificationCallBack: ' + JSON.stringify(jsonData));
$rootScope.openedFromNotification = true;
alert($rootScope.openedFromNotification);
// $ionicHistory.clearCache();
// $window.location.reload(true);
$rootScope.$broadcast('app:notification', {refresh: true});
};
As you can see I've created a custom event app:notification
and used the $rootScope
to broadcast it ($broadcast
) to the children scopes.
I've attached an object with some info your receiver can use.
Now in your controller you can intercept the event using $scope.$on
and call your refresh function:
angular.module('starter.controllers',['ionic'])
.controller('MainCtrl', function($scope, $rootScope, $http) {
$scope.$on('app:notification', function(event, data) {
console.log(data);
if (data.refresh)
{
$scope.doRefresh();
}
});
});
NOTES:
You don't really need to clean the cache here $ionicHistory.clearCache();
.
Upvotes: 3