I am using angular-ui in my project and I wanted to implement a modal window. Most of the components of the library (http://angular-ui.github.io/bootstrap/) are implemented as directives (as expected). However, modal is not - it is implemented as a service. This leads to a strong dependency on the view in the controller (i.e. the controller needs to know that the view uses a modal window, what should not be the case).
My question is: why is modal implemented as a service, not directive? Does it give any benefits?
The $modal
directive is quite flexible, and by its API, it supports:
- Being triggered on any event you want, since the controller controls when it opens.
- Passing data from the controller to the controller in the dialog, using the
resolve
option
- Using any controller or template in the dialog.
- Passing data back from the dialog on close to the triggering controller, by its
result
promise.
While not impossible for this to all be in a directive, I think it could only realistically be achieved by using a lot of options, or a complicated object, which would have to be constructed in the controller anyway.
Another reason for this not being a directive, is that directives are usually for things in a particular place in a page. The modal by its very design is not attached to any element in the page.
I would suggest trying to design an API for a directive that gives the same functionality as $modal
, and I suspect it'll reveal that using a service is, on the whole, clearer, and probably more flexible.