retain angular variables after page refresh

好久不见. 提交于 2019-11-27 14:59:44

You can use localStorage. It is really easy to use.

var token = "xxx";
localStorage.setItem("token", token);
localStorage.getItem("token"); //returns "xxx"

When you refresh a page all your JavaScript context is lost (including all data saved in variables).

One way to maintaing information from one session to another is to use the browser's localStorage. In your case, you probably want to check ngStorage.

I did the same using $window.localStorage.

It is kind of similar to accepted answer.

var token = "xxx";
$window.localStorage.setItem("token",token);
$window.localStorage.getItem("token"); //returns "xxx"
$window.localStorage.removeItem("token"); //deletes token

you can use cookies

To put simple variable

$cookies.put('user', 'abc');

To save object

$cookies.putObject('objSocket', anyObject);

and to get back data from cookies use

$cookies.getObject('objSocket');

and

$cookies.get('user');

To use above code cookies.js cdnjs is :

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0-rc.0/angular-cookies.min.js"></script>

Now inject $cookies into your controller and ngCookies into your app.js

for more detail https://docs.angularjs.org/api/ngCookies

use `localStorage.setItem("key",value);` to set the value.
use `localStorage.getItem("key");`to get the value.
use `localStorage.clear();`to clear the value which is set
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!