简体   繁体   中英

Phonegap + AngularJS - back button behavior

I've been trying to override Android's back button in my AngularJS application for a few hours and I just can't do it. I've been able to make the back button stop from working, but I can't make it go back or even make it go to the home page. I'm not using routes - instead, I'm simply switching the page so I'm not even sure it's possible to go back. If I could go to the home page It'd be great. Here's my code:

  var onDeviceReady = function(){
   document.addEventListener("backbutton", handleDeviceBackButton, false);
}
function handleDeviceBackButton(){
  angular.element('[ng-controller=AppCtrl]').scope().goHome();
  menu.setMainPage('home.html', {closeMenu: true});
}

document.addEventListener("deviceready", onDeviceReady, false);

If you want only need to go back use

$window.history.back();

However, I suggest you use a routing solution like ui-router . Using $state, navigation is simpler:

$state.go('home');

Instead of adding an event listener via PhoneGap you can rely on browser back button. Your app is a webpage so triggering back button on Android will go back in your history state . Avoiding device events allows you to debug your code right in the desktop browser.

If you want to block a specific back state or do a redirect you would use:

$rootScope.$on('$stateChangeSuccess', function (ev, to, toParams, from, fromParams) {
   if (from.name == "splashscreen" && to.name =="home"){
     //redirect using navigation $state service
   }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM