There is a problem many Angular developers may come across when using Twitter Bootstrap Modals (Overlays). First of all, if you are using Angular with Twitter Bootstrap's Javascript I recommend using Angular.ui bootstrap  ⇾  less JS+HTML code  ⇾  less worries.

What is the problem? - Open a modal at a certain state

Normally when opening a Modal there is no URL change, so users can't copy the link and go directly to the modal window. Also the back button will not close the modal window and return to the previous page. Same goes for the forward button.

Solution: modalStateProvider

I am not pleased with the solution given by the Angular-ui Router FAQ answer, because I will have more than one "modal states", which results in code duplicates. That's why I found different stackoverflow questions with different solutions[1][2], but what I want to show in this article is not only the solution of the main problem, but also how you can use it to update the page behind the modal when the modal closes.

Here comes the coded solution, I will describe below how it works in detail.

[gist id="b2cbdb413d9bce1ba0c0"]

The code example has 2 States/URLs:

  1. Page with a list of projects
  2. Modal window for creating a project

A link to "projects.new" will automatically open up the modal window. After creating a project, the list of projects should automatically be updated (without requesting the projects list again). This is accomplished by setting an attribute called "modalResult" on the parent state ("^" = "projects").

In Detail: Angular-ui Bootstrap Modal automatically adds 2 $scope functions: $close(result) and $dismiss(reason). I am using $close to pass a result to the success callback function of the 'closing' event of the modal instance.

To get the result in the parent controller/state you need to $watch the current state modalResult. If there is a result, it means the modal has closed by successfully creating a project and you can add the project to the projects array.

I think the whole workflow is not so easy to explain, but if you think it through it should make some sense ;)  If you have any questions or improvement suggestions - feel free to comment below!

[1] http://stackoverflow.com/questions/24713242/using-ui-router-with-bootstrap-ui-modal [2] http://stackoverflow.com/questions/13812962/modal-window-with-custom-url-in-angularjs

Try lingohub 14 days for free. No credit card. No catch. Cancel anytime