我在离子应用程序中使用此控制器来检查新消息或活动,如果有消息则添加徽章:
.controller('checkNew', function($scope, getNewMsg, getNewAct, $localstorage, $cordovaLocalNotification, $http, $state) {
getNewMsg.getNew(function(data) {if(data!=0){$scope.addActivity(data);$scope.counterAct = data}else{$scope.cancelAllNotification}});
getNewAct.getNew(function(data) {if(data!=0){$scope.addNotification(data);$scope.counter = data}else{$scope.cancelAllNotification}});
这就是我的.factory getNewMsg:
.factory('getNewMsg', function($http, $localstorage, $timeout){
return {
getNew: function(callback){
var user_id = $localstorage.get('user_id');
var timer;
function myLoop(){
timer = $timeout(function(){console.log( "Timeout executed")},5000);
timer.then(
function(){$http.post('http://www.digitalxp.it/appwork/include/check_msg.asp?id='+user_id).success(function(data){callback(data)}).error(function(){alert("Errore di comunicazione!")});myLoop()},
function() {console.log("Timer rejected!")}
);
}
myLoop();
}}
})
我的问题是我每次都要在控制台中添加徽章来调用控制器,但我只会检查一次,并在应用程序的所有离子视图上查看徽章! (也是消息项附近的侧边菜单!)
我认为有可能使用指令,但我不知道如何开始!
答案 0 :(得分:0)
我已根据您的要求对此进行了更新以使用广播,现在您的控制器将注册到活动newMessageReceived
并将每5秒更新一次。此外,这更像是一项服务,因此我将模块更新为服务而非工厂。
请注意,我已将timer.then(setNew, handleError);
更改为timer.then(setNew(), handleError);
.controller('checkNew', function($scope, messageService, getNewAct, $localstorage, $cordovaLocalNotification, $http, $state) {
//register to broadcast and update when the messages are updated
messageService.newMessageReceived($scope, updateMessage)
function updateMessage(message) {
if(message){
$scope.addActivity(message);
$scope.counterAct = message;
} else {
$scope.cancelAllNotification
}
}
});
.service('messageService', function($rootScope, $http, $localstorage, $timeout){
/* Initialization */
//setup timer to run every 5 seconds
var timer = $timeout(timeoutFunction, 5000);
//set the actions for resolve and reject
timer.then(setNew(), handleError);
function timeoutFunction() {
return;
}
function handleError() {
console.log('Timer rejected');
}
//every time the newMessageRecieved event is broadcasted, run the callback and register the scope
function newMessageReceived(scope, callback) {
callback(getNew());
scope.$on('newMessageReceived', function() {
callback(getNew());
});
}
function getNew() {
return $localstorage && $localstorage.message || undefined;
}
function setNew() {
var user_id = $localstorage.get('user_id');
return $http.post('http://www.digitalxp.it/appwork/include/check_msg.asp?id='+user_id)
.success(function(data){
$localStorage.message = data;
$rootScope.$broadcast('newMessageReceived');
})
.error(function(){alert("Errore di comunicazione!")})
}
return {
newMessageReceived: newMessageReceived
};
});