Modals Persist Between States

UPDATE : This is not really an issue. See last comment from me.

There have been a few posts about problems with modals. Sometimes they don’t close. I’ve got a few cases where if I do things just “right”, a modal is stuck open and cannot be closed at all. It takes a bit of work to make it happen though.

Tonight, I came across another issue that concerns me. Right now, if a modal is ever opened, it will stay in the DOM for the life of the app even after the modal is closed. It stays in the DOM even when navigating to different states.

I’m a bit worried about that being a performance problem. What if the modal was a form with directives, watches, etc. It’s going be slowing down the digest cycle. Perhaps it’s still watching for scroll events that can never happen?

Tonight, I noticed a new “issue” with modals that are closed. They mess up other forms! For example, I have a modal that pops up when a user tries to access their account on the app. It asks for a passcode. Once the passcode is entered, the modal closes and takes them to their friends list ( a new state). Then, they can tap on a friend and go to the messages from the that friend (another state). Yet, the modal is still sitting in the background. Then, when the user begins to type a message in a form with only one field, the lovely iOS keyboard bar (Previous, Next, Done) buttons show there is another field to “tab” to even though there really is not. It’s the form on the closed modal that the keyboard can still see. This is very confusing for a user.

I feel like once a modal is closed, it needs to be deleted from the DOM. To “solve” this problem for now, I’m using an ng-if on the content in the modal. If the modal is actually open, I display the content. If the modal is closed, the ng-if removes the content from the DOM. However, that still leaves at least 1 watch for the ng-if. Would it be more performant for modals to actually be removed completely?

Example where there is really only one field on the form. Notice the “Next” button?

Actually, this is a bit worse than I thought. Right now, if you go to multiple states that have modals and open the modal, you get numerous modals on the DOM.

Example :

Go to Page A that has modal.
Open modal
Navigate to page B.
Go back to Page A.
Open Modal.

You now have 2 modals in the DOM.

At some point in the past, I was pretty sure that Ionic only allowed one modal on the DOM at once. However, I can’t find that in the code anymore.

Okay, I found the cure for this. My solution is to use stateChangeStart on any page that had a modal. When stateChangeStart fires, I remove the modal from the scope like :

$scope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams){
  $scope.modal.remove();
});
2 Likes

Thx, for the tips.
I have the same problem and this solve it :wink:

Wow, nice catch! That explains some weirdness I’d seen in my app.