ionic-frameworkionic-view

How to prevent Ionic modal from hidding


I catch modal.hidden event, and do some check on it. When the check is false, I want to prevent the modal from hiding. I use e.preventDefault(). But it doesn't work.

My code & CodePen:

$scope.$on('modal.hidden', function(event) {
    var isPassed = false;
    // do some check
    if (isPassed == false) {
        event.preventDefault();
    }  
});

Solution

  • You can use the backdropClickToClose and hardwareBackButtonClose option when setting up the modal and also hide the back button. This will prevent the modal from being closed:

    // Load the modal from the given template URL
    $scope.modal = {};
    $ionicModal.fromTemplateUrl('my-modal.html', {
        scope: $scope,
        animation: 'slide-in-up',
        backdropClickToClose: false,
        hardwareBackButtonClose: false
    }).then(function(modal) {
        $scope.modal = modal;
    });
    

    You can then do some check and set those values to true again, and also show the back button. This will still be user friendly and the user can close the modal in a proper way.

    function checkSomething(){
        // The timeout is only to demonstrate, do your check here
        $timeout(function(){
          console.log("Now user can close modal")
          $scope.isPassed = true;
          $scope.modal.backdropClickToClose = true;
          $scope.modal.hardwareBackButtonClose = true;
        }, 3000)
    }
    

    Updated codepen here