只是为了扩大@ KhanhTo的Another option
行:
;(function initModule(module) {
module.provider('IsOnlineService', Provider);
function Provider() {
var eventNames = {
online: 'online',
offline: 'offline'
};
this.setOnlineEventName = function(name) {eventNames.online = name;}
this.setOfflineEventName = function(name) {eventNames.offline = name;}
this.$get = OnlineService;
OnlineService.$inject = ['$document', '$rootScope'];
function OnlineService($document, $rootScope) {
// Listen events
$document.addEventListener(eventNames.online, setState.bind(this, true), false);
$document.addEventListener(eventNames.offline, setState.bind(this, false), false);
// Observer pattern: everybody can receive updates
var subscribers = {};
this.subscribe = subscribe;
this.unsubscribe = unsubscribe;
var state = false;
this.getState = getState;
return this;
// Implementation
function subscribe(id, sub) {subscribers[id] = sub;}
function unsubscribe(id) {delete subscribers[id];}
function announceAll(value) {
Object.keys(subscribers, function(id){
subscribers[id](value);
});
}
function getState() {return state;}
function setState(value) {
state = value;
$rootScope.$apply(announceAll.bind(null, state));
}
}
}
})(angular.module('yourModule', [
]));
配置:
angular.module('app')
.config(['IsOnlineServiceProvider', function(online){
online.setOfflineEventName('away');
}]);
用法:
但愿$范围$手表监听器需要放置在每一个控制器? – jcm
@cookiemonster:是的,否则你怎么能通知? –
@cookiemonster:如果您只需要'noNetwork'在视图中进行绑定,则您甚至不需要$ watch,因为您的子范围将从根作用域继承此属性。 –