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

angularjs, angularjs-scope, javascript

Solution

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.

Problem

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.

Original source