Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$rootscope value used in a controller is overridden when refreshing the page used with that controller

In my angularjs page I am passing a global data to another controller using the $rootscope object of angularjs. In my controller i am successfully able to catch the value stored in $rootscope object and the value is populating correctly and i am using the value in a label contol. But when I am refreshing the page the value is getting disappeared . What is the problem in this and how cam I overcome this situation.

$scope.loginname = $rootScope.curusername;

Thanks and regards Utpal

like image 532
Utpal Avatar asked Mar 20 '23 19:03

Utpal


2 Answers

If you reload your page all information that you store in JavaScript variables are lost. $rootScope is nothing more then a variable in JavaScript. If you want to store something that persists a page reload there are at least the following possibilities:

  • use a Cookie (in angular you could use the $cookieStore)
  • use some of the new HTML5 features like Locale Storage, Web DB or the old DOM Storage (http://en.wikipedia.org/wiki/Web_storage)
  • store your data on a server
like image 80
michael Avatar answered Mar 23 '23 08:03

michael


Ok Utpal a few things to note here:

  • AngularJS will not persist between a full page reload, you have to use another mechanism to persist data between two different loads, like HTML5 localStorage or Cookies etc. The reason why refreshing the browser deletes your data is because the entire AngularJS app is being torn down and reloaded, so can't expect it to maintain state.

  • If you want to persist data between controllers, $rootScope isn't the best way. You should look up angularJS services and use them to communicate between controllers.

Hope this helps!

like image 21
Mutahhir Avatar answered Mar 23 '23 09:03

Mutahhir