$mdDialog with a confirmation dialog

$mdDialog from the angular material library, is a very good looking popup for almost anything in your app.  It has evolved in a way that many of the hacks (i.e. using it as a regular popup) are no longer necessary.

One thing that I was asked to do in a recent project was to create a confirmation popup from another custom popup.

The issue is that currently in order to open a popup, you have to close the current popup.

Here’s a small demo that demonstrates it:

Notice that you open one dialog,it opens with a button.  This button opens a new dialog, but closes the first.  Now, assuming you want the user to confirm some action, it is quite probable you would have a use case in which the user should be returned to the “parent” dialog.

While this is a long time asked feature (it starts here: https://github.com/angular/material/issues/698, but goes on with several more requests later on), it is not officially supported yet.  Looking at the ngMaterial dialog code shows that the mechanism for this is already in place – and you can use it right now.

This line in the code hints that a skipHide property can be added to the dialog’s options. Adding it to the options, does enables the wanted effect – the “parent” dialog remains while we confirm:

Works really nice, right?

One thing I’ve noticed was, that projects that use an older version of ngMaterial (e.g. 0.10.x or 0.11.x) would have to go an extra mile for this to work.  While skipHide would have kept the “parent” dialog while the user confirms, a confirmation would have removed the “parent” dialog as well.  This is not the desired effect. It happens because the dialog’s scope was being $destroyed, and the mdDialog directive was listening for the $destroy event.  Here’s how it works with v 0.11.4:

If your projects relies on an older version, and it would be too hard upgrading (mostly for css issues), you can use the preserveScope property in the options to solve this:

It’s great to see that ngMaterial progresses faster than the documentation shows 🙂

When include a directive inside the dialog (by ‘template’ property), there is problem, how to close the dialog? From the inner directive, or from the dialog ?

So for that we have simple manner to define an additional controller inside the dialog function. In the additional controller we will define the hide function.  Now we are able to include that hide function inside the ‘template’ property of the dialog function.

2 thoughts on “$mdDialog with a confirmation dialog

Leave a Reply