简体   繁体   中英

In Ionic, how to ask users to confirm before leaving a page? If No is chosen, how to cancel the leaving behavior?

I've written the codes in the $ionicView.beforeLeave event handler. But it seems not effective. Because when this event happens, the page has been shifted, so it's too late to popup the confirming dialog. And I don't know how to prevent the default behavior of this event. I've tried event.preventDefault() , but it's useless. Anyone can help me? Thanks in advance!

 $rootScope.$on("$ionicView.beforeLeave", function (event, view) { $ionicPopup.confirm({ title: "Confirm", template: "Data has been modified. Are you sure to discard the changes and leave anyway?" }).then(function (res) { res || event.preventDefault(); }); }); 

If you are using the default ui-router then an option would be to subscibe on the $stateChangeStart event.

$rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
    // Navigation will be prevented
    if (!some_check_variable) {
        event.preventDefault(); 
    }
});

You can read more on the ui-router documentation here: https://github.com/angular-ui/ui-Router/wiki

check the stateChangeStart section

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