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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With