ionicHistory: Going to a different state if no back views/states

I have a network error screen which shows when device is offline. When devices reconnects, a button on the screen takes the user to the previous state using “$ionicHistory.goBack()”.

Function:

        $scope.myGoBack = function () {
            $ionicHistory.goBack();
        };

HTML:

 <button class="button button-full button-energized" ng-click="myGoBack()">Continue</button>

My issue is that if device is offline and app is launched, there is no back view to navigate to. So the button doesn’t do anything. Is there any way to get the length of the history and setup the function in a way, so it navigates to a different state if there are no back views, and goes back if there are.

Any help is appreciated… Thanks!

I have solved it myself:

// Get the length of the history stack
        var histId = $ionicHistory.currentHistoryId();
        var hist = $ionicHistory.viewHistory().histories[histId]
        var histLength = hist.stack.length;

        $scope.histLength = histLength;

        // Continue button function
        $scope.myGoBack = function () {

            if (histLength <= 2) {
                // If no prev state, go to custom state 
                $state.go("stateName");

            } else if (histLength > 2) {
                // otherwise go back
                $ionicHistory.goBack();
            }
        };

HTML (button):

<button class="button button-full button-energized" ng-click="myGoBack(histLength)" ng-disabled="! isOnline">Continue</button>