At Fundoo Solutions, we found ourselves having the need to show popup dialogs in the multitude of projects we have worked on. We always ended up using Twitter bootstrap, and we loved their modal dialogs. But we found it very restrictive, or needing a lot of customization to make it look and behave how we wanted it to. So, we took their CSS, and added our own functionality, and ended up with what we are calling AngularJS Popup Dialog or AngularJS Modal Service.
Why create the AngularJS Popup Dialog Service?
As we mentioned, we found ourselves redoing the same stuff again and again. Style the contents differently, need a different controller on each modal, pass in some content to the modal to display it, etc. We thought of making it a directive, but that had its own implications. We ended up making it a service, because:
- We didn’t want to pollute the DOM with the modal content unless the modal was to be displayed. So we defer it till the point the service is called.
- Passing the data into the modal with a directive would need custom attributes (that would differ from modal to modal). That would also imply the data would have to be put on the scope before it could be passed in, which is not always convenient.
How do I use it?
We export the service ‘createDialog‘ as part of the ‘fundoo.services‘ module. We can then call the createDialog service as a function directly, passing in the following arguments
createDialog(templateUrl, otherOptions, argumentsForController)
Thats about it. You will need
- Bootstrap CSS
When this function is called, a modal is poped up, with the template specified in the template URL becoming the body of the modal dialog. What else you can change and pass to the service in otherOptions and argumentsForController is covered in the next section. This is what happens when you call the service:
What can I change?
In addition to modifying the template body, with the AngularJS Popup Dialog service, you can change the
- ID of the dialog (and the class for the modal)
- Title at the top of the dialog
- Whether or not to show a backdrop behind the popup (and the class to use for the backdrop)
- The template for the footer (so that you can change what buttons to show)
- The function to call on success!
- A controller to attach to the modal
In addition, as part of the third argument, you can pass an object with keys and values. Each key can then be accessed through the controller’s constructor arguments.
Can I see it in action?
Sure. Go ahead take a look at the example here.
Where can I learn more?
We have open-sourced this code (the first of many more to come soon, we promise!) and it is now available for your perusal and reuse at this link. Feel free to use it as it is, or modify the heck out of it. Do let us know if you like it, and feel free to send us a pull request if you have some changes which you think everyone can benefit from.