How to check internet connection in AngularJs

angularjs

Solution

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.

Problem

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?

Original source

Related problems