在Ionic中,如何在离开页面之前要求用户确认?如果选择否,如何取消离职行为?

时间:2017-05-26 07:36:15

标签: javascript angularjs cordova ionic-framework

我已经在$ionicView.beforeLeave事件处理程序中编写了代码。但似乎没有效果。因为当这个事件发生时,页面已被移动,因此弹出确认对话框为时已晚。我不知道如何防止此事件的默认行为。我试过event.preventDefault(),但它没用。有人可以帮帮我吗?提前谢谢!

$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();
  });
});

1 个答案:

答案 0 :(得分:0)

如果您使用的是默认的ui-router,那么选项就是$stateChangeStart事件的subcibe。

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

您可以在此处阅读有关ui-router文档的更多信息:https://github.com/angular-ui/ui-Router/wiki

检查stateChangeStart部分

相关问题