How to redirect users if there is no Internet connection in Ionic framework?

profile for Nikola at Stack Overflow, Q&A for professional and enthusiast programmers
I’m a big fan of Stack Overflow and I tend to contribute regularly (am currently in the top 0.X%). In this category (stackoverflow) of posts, I will be posting my top rated questions and answers. This, btw, is allowed as explained in the meta thread here.

As you may know, I’m really into Ionic framework lately and am helping out on StackOverflow with the knowledge I gained so far with the framework. In the last 30 days, I’m the top answerer in the ionic tag, and am currently #6 All time answerer:

soIonic

I answered this question by userFlorin Simion:

I want to redirect users to a different page when they’re not connected to the Internet.

My only question is why this is working:

if (window.Connection) {
    if(navigator.connection.type == Connection.NONE) {
        alert("Please connect to internet");
    }
}

and this is not

if (window.Connection) {
    if(navigator.connection.type == Connection.NONE) {
        $scope.state.go('offline');  
    }
}

My answer was:

Because you’re using $state the wrong way. Instead of this:

$scope.state.go('offline');

You should do it like this:

$state.go('offline');

Remember to inject $state in your controller. More information about $state from official docs.

By “Remember to inject $state in your controller” I’m referring, for example, to this:

app.controller('ctrl', function ($scope, $state) {
    $scope.changeState = function () {
        $state.go('someplaceNice');
    };
});

If you would want a more in-depth tutorial about network information gathering in Ionic make sure you check the Check network information change with Ionic framework tutorial.

Written by Nikola Brežnjak