Bootstrap Modal window with custom URL in AngularJS
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.
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, 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.
The code example has 2 States/URLs:
- Page with a list of projects
- 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!