How to check internet connection in AngularJs

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.


It's definitely not as nice, but you could just try an AJAX request to your web server; it'll either succeed or time out.

Also, the HubSpot/offline project looks really good.

Tags:

Angularjs