Hawkhunter Hawkhunter - 1 month ago 28
AngularJS Question

Ionic Soft Backbutton, $rootScope.IonicGoBack

I am creating a project, and still with ionic1.

I have three pages Home(Playlists) <-> Second(discover) <-> third(myth)

Each page has a soft back button created by ionic default templates for a top menu page.

How ever when I go to the third page, and press back twice (to go back to home) it stops at the Second page.

Myth Code:

$rootScope.$ionicGoBack = function (backCount) {
console.log("check");
$ionicViewSwitcher.nextDirection('back');
$state.go('app.discover');
};


Discover code:

var doCustomBack = function () {
console.log("hey");
$state.go('app.playlists');
};

// override soft back
// framework calls $rootScope.$ionicGoBack when soft back button is pressed
var oldSoftBack = $rootScope.$ionicGoBack;
$rootScope.$ionicGoBack = function () {
doCustomBack();
};


I have tried multiple ways, I needed to override the back button and changed it to $state.go, this used to be $ionicHistory.goBack(-2) etc etc How ever there was a bug with that and changed it.

What is weird is: When I go to Second page and go back, it works fine prints "hey" and goes back to main page. When I go to Third page then go back to Second it doesnt work, HOWEVER When I go back to the third page AGAIN and go back to the second page, the back button on the second page works.

There is no error either...

If there is someone with some knowledge on this this would be awesome.

Thanks in advance.

Answer

And besides what I wrote in comment, try this code. It's a run function in app.js

.run(function($ionicPlatform, $state, $ionicHistory, $rootScope) {

    $state.backbutton = 0;

    $ionicPlatform.registerBackButtonAction(function(event) {

    if ($state.current.name == "app.home") { // whatever your first state is
        if ($state.backbutton === 0) {
            $state.backbutton = $state.backbutton + 1;               
        } else {
            navigator.app.exitApp();
        }
    } else {
        history.go(-1);
        $ionicHistory.nextViewOptions({
            disableBack: true
        });
     }
   }, 100);

});
Comments