Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check internet connection in AngularJs

Tags:

angularjs

This is how I would check internet connection in vanilla javascript:

setInterval(function(){     if(navigator.onLine){         $("body").html("Connected.");     }else{         $("body").html("Not connected.");     } },1000); 

I have angular controllers and modules in my project. Where should I put the code above? It should be executed in global context and not be assigned to a certain controller. Are there some kind of global controllers maybe?

like image 289
UpCat Avatar asked Apr 26 '13 17:04

UpCat


People also ask

How to check the internet connection in Angular?

Step 1: You can install angular CLI, to prepare a basic project skeleton. Step 2: Create a new project for your workspace. It will create a basic skeleton or structure for your project. It will handle operations to check the status of your internet connection, whether it is online or offline.

How do I know if JavaScript is connected to Internet?

JavaScript has a function called navigator. This browser property can be used to determine if you are connected to the internet. It returns true or false depending on the status of the client's network and says whether the browser is online or offline easily.


1 Answers

First of all, I advise you to listen to online/offline events.

You can do it this way in AnguarJS:

var app = module('yourApp', []);  app.run(function($window, $rootScope) {       $rootScope.online = navigator.onLine;       $window.addEventListener("offline", function() {         $rootScope.$apply(function() {           $rootScope.online = false;         });       }, false);        $window.addEventListener("online", function() {         $rootScope.$apply(function() {           $rootScope.online = true;         });       }, false); }); 

NOTE: I am wrapping changing of root scope's variable in $apply method to notify Angular that something was changed.

After that you can:

In controlller:

$scope.$watch('online', function(newStatus) { ... }); 

In HTML markup:

 <div ng-show="online">You're online</div>  <div ng-hide="online">You're offline</div> 

Here is a working Plunker: http://plnkr.co/edit/Q3LkiI7Cj4RWBNRLEJUA?p=preview

Other solution could be to broadcast online/offline event. But in this case you need to initialize current status upon loading and then subscribe to event.

like image 110
Valentyn Shybanov Avatar answered Sep 18 '22 12:09

Valentyn Shybanov