Where do I put event listener code in AngularJS that all controller use?

I want to have some event listener code in my AngularJS app which will apply to the scope of all controllers.

I basically want to define the following somewhere:

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

which will receive events no matter which controller scope is currently active.

Answers


Try $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;
        });
    }
});

Due to scope inheritance, $rootScope's properties will be inherited by all your child scopes. Be aware that this event occurs outside angular, the use of $apply is also necessary in this case. All your child scopes can $watch noNetwork changes. Like this:

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

Another option is creating a service to hold the noNetwork property and inject that service into your controllers.


You could add this in your top controller and your child controllers would see the value for $scope.noNetwork


Just to expand @KhanhTo's Another option row:

;(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', [
]));

Configuration:

angular.module('app')
.config(['IsOnlineServiceProvider', function(online){
  online.setOfflineEventName('away');
}]);

Usage:

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';
  });
}]);

Need Your Help

how do i find which process is leaking memory

linux ubuntu memory-leaks

I have a system (Ubuntu) with many processes and one (or more) have a memory leak. Is there a good way to find the process that has the leak? Some of the process are JVMs, some are not. Some are home

Gmail API - Parse message content (Base64 decoding?) with Javascript

javascript angularjs base64 gmail-api

I'm trying to use the Gmail API to get a user's email, grab the message subject and body, and then display it on a webpage. I'll be doing other stuff with it, but this is the part that I am having