Angular scope variable not persisting when using back button?

I have an AugularJS controller that has something like the following on initialization

$scope.urlChanged = false;
and the url is like /firstpage/test

      

There is a button on the page, and when the user clicks the button, it executes

$scope.urlChanged = true;
window.location = '/secondpage/test';

      

The page goes to / secondpage / test as expected. Clicking the Back to Back button returns the page to /firstpage/test

. But $scope.urlChanged

- false

and not the final true. Is this expected in Angular? How do I do $scope.urlChanged = true

when I return?

+3


source to share


2 answers


Scope variables are not persisted across navigation. In fact, even services will not retain their values ​​/ state. When you navigate with a browser, you are actually requesting a completely new angular app.

This is not an angular bug. This is how the browser is expected to process the new request. The way to store data in this case is to store any data in what will persist between requests.

As I see you have three options (ish):



  • Save state in cookies: Supported by almost all browsers, but be careful to treat them as client cookies, or you may not be able to save data on a page you didn't submit (which is due to your issue when navigating back in the browser).
  • Save server. This has the same problems as server side cookies. You need to send data to the server for it to be saved - which you could do with ajax and "auto-save" calls with a timeout function. You also need a way to keep track of who you are so that you can get the correct data from the server, which is often done with cookies, but can be done with querystring parameters, but also with (basic) authentication.
  • LocalStorage. This is my favorite option and is very well supported unless you need to support legacy IE browsers. There are good frameworks out there designed for angular making it easier to use, and some even have a cookie backup if they are not supported.

Check this link for LocalStorage support: https://github.com/grevory/angular-local-storage

+2


source


When the view changes, the new controller enters the image and the instance of the previous view instance ends. Also, since each controller has its own private resource, which is destroyed after the view is changed, to avoid confusion.



0


source







All Articles