Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 989
jcm Avatar asked Jan 30 '14 08:01

jcm


People also ask

Can I add event listener to all elements of class?

To add an event listener to all elements with class: Use the document. querySelectorAll() method to select the elements by class. Use the forEach() method to iterate over the collection of elements.

Which is the correct method to add an event listener?

The method addEventListener() works by adding a function, or an object that implements EventListener , to the list of event listeners for the specified event type on the EventTarget on which it's called.

Where are event listeners stored?

Event classes are typically stored in the app/Events directory, while their listeners are stored in app/Listeners . Don't worry if you don't see these directories in your application as they will be created for you as you generate events and listeners using Artisan console commands.


1 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.

like image 116
Khanh TO Avatar answered Oct 18 '22 05:10

Khanh TO