问题
So two questions.
How does angular applications handle refresh page, b/c from what I heard, $rootScope destroy() on refresh and application gets re-run and re-config -ed, and I was wondering if there's an elegant way to preserve the $rootScope without having to store $rootScope variables as a string into a storage.
If I load a template on a directive that loads a modal on the page, is it possible to configure history to not navigate but to revert the open modal. and due to validations and such, I do not think it is possible to implement same function using href.
回答1:
If your url's are mapped with the $routeProvider
, you can reload a controller invoking $route.reload()
. This refresh the page without destroy the $rootScope.
I have create a plunker to show this. The controller counts how many times the page has been reloaded.
回答2:
There is probably no way to preserve any javascript variable through a page reload and $rootScope is just a javascript variable.
It seems though that what you are looking for is a way to make your application "start from the same point" that it was left at when a page was reloaded. I would recommend you to get familiar with notion of state. Every application can be viewed as a set of states and transitions between them. Every user interaction or any other actions that happen within applications either change the state of application or keep it in the same state. For example: clicking a user link from a list of users changes the state from "view users list" to "view user details for user with id=213", clicking an "Edit" button on "view user details for user with id=213" changes state to "edit user with id = 213". And as those transitions take place variables are being assigned values, views change, requests get sent out etc.
The two things that are needed for "start from the same point" problem are state manager and a way to serialize and store states.
As a state manager besides the core $router directive you can use ui-router. As for a way to serialize and store a state with ui-router does this through URL. The benefit of ui-router over core $router is that it allows for nested states and is generally more flexible.
ui-router has also a solution for your second question in its github wiki https://github.com/angular-ui/ui-router/wiki/Frequently-Asked-Questions#how-to-open-a-dialogmodal-at-a-certain-state
回答3:
Could you not use window.localstorage to preserve your js variables? That way if the user refreshes the page outside of the app you could reload your values
来源:https://stackoverflow.com/questions/17324902/how-does-angular-application-handle-refresh-page-and-could-we-use-history-on-lo