Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs: Why page refresh destroy the values of $rootScope?

In my local route http://localhost:9000/#/deviceDetail/ I have a controller that manage that view. Before going to that view I set some variables to the $rootScope (for example $rootScope.dashboards).

Once on that view I have acces to dashboards property, but when I refresh the page with F5 key for example the property dashboards is lost.

I tried to save the $rootScope on the localStorage variable but I got circular reference problems with the JSON.stringify method.

Any tip to manage that?

like image 610
gabrielAnzaldo Avatar asked Apr 24 '15 14:04

gabrielAnzaldo


Video Answer


2 Answers

AngularJS is a JavaScript framework, everything is stored in memory heap and the heap is starts when you open a page and it's destroyed after you close it. In this context, browser refresh is like closing and re-opening the page.

To keep the value after refresh, you should store it in a cookie, for this you use for example $cookies or sessionStorage / localStorage as recommended by M K.

like image 185
Marko Gresak Avatar answered Sep 20 '22 08:09

Marko Gresak


I tried to store auth token using cookies following the article at Getting started with AngularJS and ASP.NET MVC - The long awaited Part Three. But the cookies is destroyed whenever I hit F5 or refresh the Chrome browser.

That article says ngCookies helps to deal with page refresh to maintain token for page refresh. And I had thought it did and I did not know ngCookies killed me. It was destroyed if page is refresh! after hours to research online I see this article helps me.

According to M K, I used localStorage (or sessionStorage) helped me to get rid of the headache of cookies. Using cookies to store authentication token or something else is a bad idea. I ran into that problem and I got lost (did not know the bug coming from "using cookies") as the above article mentioned/confirmed. So, it was a bug in that article.

Thank you million times, M K.

like image 40
Thomas.Benz Avatar answered Sep 22 '22 08:09

Thomas.Benz