我正在尝试将以下控制器重写为服务,以便可以在ng-show
指令中从我的视图中调用它,但我目前正在努力。它需要是一个服务,以便它返回true或false值,并且可以在整个应用程序中重用:
module.controller('MyCtrl', function($rootScope, $cordovaNetwork)
document.addEventListener("deviceready", function () {
var type = $cordovaNetwork.getNetwork()
var isOnline = $cordovaNetwork.isOnline()
var isOffline = $cordovaNetwork.isOffline()
// listen for Online event
$rootScope.$on('$cordovaNetwork:online', function(event, networkState){
var onlineState = networkState;
})
// listen for Offline event
$rootScope.$on('$cordovaNetwork:offline', function(event, networkState){
var offlineState = networkState;
})
}, false);
});
这是我到目前为止所做的,目前还没有工作:
(function() {
'use strict';
angular
.module('dingocv.services')
.service('ConnectionService', ConnectionService)
function ConnectionService($rootScope, $cordovaNetwork) {
this.isOnline = function() {
var type = $cordovaNetwork.getNetwork()
var isOnline = $cordovaNetwork.isOnline()
var isOffline = $cordovaNetork.isOffline()
$rootScope.$on('$cordovaNetwork:online', function(event, networkState)) {
return networkState;
}
$rootScope.$on('$cordovaNetwork:offline', function(event, networkState)) {
return networkState;
}
}
}
})();
答案 0 :(得分:1)
如果我理解了这个问题,我的解决方案如下:
//这是服务
.factory('ConnectivityMonitor', function($rootScope, $cordovaNetwork){
return {
isOnline: function(){
if(ionic.Platform.isWebView()){
return $cordovaNetwork.isOnline();
} else {
return navigator.onLine;
}
},
isOffline: function(){
if(ionic.Platform.isWebView()){
return !$cordovaNetwork.isOnline();
} else {
return !navigator.onLine;
}
},
startWatching: function(){
if(ionic.Platform.isWebView()){
$rootScope.$on('$cordovaNetwork:online', function(event, networkState){
console.log("went online");
});
$rootScope.$on('$cordovaNetwork:offline', function(event, networkState){
console.log("went offline");
});
}else {
window.addEventListener("online", function(e) {
console.log("went online");
}, false);
window.addEventListener("offline", function(e) {
console.log("went offline");
}, false);
}
}
}
})
要检查整个应用程序的网络状态,我只需使用(在控制器中):
.controller('MyCtrl',['ConnectivityMonitor', function(ConnectivityMonitor) {
if(ConnectivityMonitor.isOnline()){
//do something
}else{
//do something else
}
}])
希望这有帮助!