我在哪里将所有控制器使用的事件监听器代码放在AngularJS中?

时间:2014-01-30 08:18:39

标签: javascript angularjs angularjs-scope

我希望在我的AngularJS应用程序中有一些事件监听器代码,它将适用于所有控制器的范围。

我基本上想在某处定义以下内容:

    document.addEventListener("online", onOnline, false);
    document.addEventListener("offline", onOffline, false);

    function onOnline() {
        console.log("just got online event");
        $scope.noNetwork = false;
    }

    function onOffline() {
        console.log("just got offline event");
        $scope.noNetwork = true;
    }

无论哪个控制器范围当前处于活动状态,它都将接收事件。

3 个答案:

答案 0 :(得分:7)

尝试$rootScope

var app = angular.module("yourModule",[]);
app.run(function($rootScope){
   document.addEventListener("online", onOnline, false);
   document.addEventListener("offline", onOffline, false);

   function onOnline() {
        $rootScope.$apply(function(){
            console.log("just got online event");
            $rootScope.noNetwork = false;
        });
    }

    function onOffline() {
        $rootScope.$apply(function(){
             console.log("just got offline event");
             $rootScope.noNetwork = true;
        });
    }
});

由于范围继承,$ rootScope的属性将由所有子范围继承。请注意,此事件发生在角度之外,在这种情况下也需要使用$apply。您的所有子范围都可以$ noNetwork更改。像这样:

$scope.$watch('noNetwork',function(newValue){
//Handle your tasks here.
});

另一种选择是创建一个服务来保存noNetwork属性并将该服务注入您的控制器。

答案 1 :(得分:0)

您可以在顶级控制器中添加它,您的子控制器会看到$ scope.noNetwork的值

答案 2 :(得分:0)

只是为了扩展@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');
}]);

用法:

angular.module('app')
.controller('SomeCtrlr', ['IsOnlineService', function(online){
  // Direct way:
  this.online = online.getState();
  this.isOnline = online.getState;
  // SubPub: 
  online.subscribe('somectrlr', function(state){
    this.isOnline = state;
    this.onlineStr = state ? 'Online' : 'Offline';
  });
}]);