Internet Connection


I have develop an application with Ionic and everything works great.
Until now in every controller use a factory to check internet connection and then if there is no internet redirect the user to a specific view.
What i want to do is instead of using it in every controller, place it somewhere like inside run, so that every view will use it from there. I want if someone choose an option from the sidemenu and there is no internet to redirect him but not detect live if he loose his connection. Just only if he select an option.
I tried the $http interceptor but i did not managed to make it work.

Thanks in advanced!

The easiest way would be to create a rootScope method in your app.js, but I don’t think it is recommended.

You should look into services, it would be the most efficient way to do this, and you can call it from every view.

A last one would be to define it in an utility file which you could refer too, but Service is the best practice in this case.

My ionic app is used on Android, iOS and for desktops (desktops bundle Chrome using electron packager). What seems to work reliably across all platforms above is putting this code in app.js

Note that I use a global $ variable to keep track ,but you can easily convert that to a factory and put in setOnline() getOnline() functions

$ = navigator.onLine;

$window.addEventListener("offline", function () {
            $rootScope.$apply(function () {
                $ = false;
                ZMDataModel.zmLog("Your network went offline");
        }, false);
        $window.addEventListener("online", function () {
            $rootScope.$apply(function () {
                $ = true;
                ZMDataModel.zmLog("Your network is online, re-authenticating");

        }, false);

For example, putting network off, switching from WiFi to LTE/3G etc all seem to trigger the right callbacks