Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
170
rated 0 times [  172] [ 2]  / answers: 1 / hits: 19194  / 11 Years ago, thu, january 30, 2014, 12:00:00

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.


More From » angularjs

 Answers
8

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.


[#72849] Wednesday, January 29, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
maya

Total Points: 418
Total Questions: 116
Total Answers: 112

Location: Mauritania
Member since Sun, Oct 17, 2021
3 Years ago
maya questions
Sun, Jul 4, 21, 00:00, 3 Years ago
Tue, Dec 22, 20, 00:00, 4 Years ago
Fri, Nov 6, 20, 00:00, 4 Years ago
Wed, Jul 29, 20, 00:00, 4 Years ago
Tue, Apr 21, 20, 00:00, 4 Years ago
;