Where do I put event listener code in AngularJS that all controller use?
17,786
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.
Author by
jcm
Updated on June 11, 2022Comments
-
jcm almost 2 years
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.
-
jcm over 10 yearsWould that $scope.$watch listener need to be placed in every controller?
-
Khanh TO over 10 years@cookiemonster: yes, otherwise how can you be notified?
-
Khanh TO over 10 years@cookiemonster: if you just need
noNetwork
to bind in the view, you don't even need $watch as your child scopes will inherit this property from the root scope.