Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular scope variable not saved when using browser back button?

I have a AugularJS controller that have something like the following when initialized

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

There is a button in the page and when user clicks the button, the following is executed

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

The page goes to /secondpage/test as expected. When clicking the browser back button, the page goes back to /firstpage/test. But the $scope.urlChanged is false, not the final value true. Is this expected in Angular? How do I make $scope.urlChanged = true when going back?

like image 253
Steve Li Avatar asked Feb 28 '26 08:02

Steve Li


1 Answers

Scope variables are not saved when you navigate. In fact not even services will retain their values/state. When you navigate with browser back you actually request a whole new angular app.

This is not angular's fault. That is how the browser is expected to handle a new request. The way to persist data in this case is saving any data in something that will persists between requests.

As i see it you have three(ish) options:

  1. Save state in cookies: Well supported by almost all browsers but take caution to handle them as clientside cookies or you won't be able to save data on a page you did not submit (excatly your problem with navigate back in browser).
  2. Save server-side. This has the same problems as the server side cookies. You need to post data to the server for it to persist - which you could do with ajax calls and 'auto-save' with a timeout function. You also need a way of tracking who you are so 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.
  3. LocalStorage. This is my favorite option and is pretty well supported, if you don't need to support legacy IE browsers. There are good frameworks designed for angular that makes it easy to use - and some even have fallback to cookies if not supported.

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

like image 178
Per Hornshøj-Schierbeck Avatar answered Mar 01 '26 21:03

Per Hornshøj-Schierbeck