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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With