4

每当用户按下 onesignal pushnotification 服务器发送的通知时,我希望我的应用程序自动刷新以从 API 检索最新数据。下面是我的示例代码,我无法从 App.js 调用控制器函数到 dorefresh()。或者是否有任何其他解决方法可以让我检索最新数据?

应用程序.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);                                
  });
})

控制器.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')
    })

};

索引.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>
4

1 回答 1

3

您可以在以下位置广播事件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});
};

如您所见,我创建了一个自定义事件app:notification并使用 将$rootScope它 ( ) 广播$broadcast到子范围。
我已经附加了一个对象,其中包含您的接收器可以使用的一些信息。

$scope.$on现在在您的控制器中,您可以使用并调用您的刷新函数来拦截事件:

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();
        }
    });
});

笔记:

你真的不需要在这里清理缓存$ionicHistory.clearCache();

于 2015-08-18T11:53:40.577 回答