I need login values for the entire project.so I'm using rootScope, but if my page is refreshed, the rootScope value gets destroyed. so instead of rootScope, I'm using AngularJS sessionStorage and now value sets successfully. Now I need to use sessionStorage value for the entire project.
how to use sessionStorage value wherever I want. I am looking for a positive replay.
Controller
if(response.data.status != null)
{
scope.User=response;
rootScope.UserId=response.data.UserId;
$window.sessionStorage.setItem("id",response.data.UserId);
scope.id = $window.sessionStorage.getItem("id");
state.go("userHome");
}
Thank you..!
I need login values for the entire project.so I'm using rootScope, but if my page is refreshed, the rootScope value gets destroyed. so instead of rootScope, I'm using AngularJS sessionStorage and now value sets successfully. Now I need to use sessionStorage value for the entire project.
how to use sessionStorage value wherever I want. I am looking for a positive replay.
Controller
if(response.data.status != null)
{
scope.User=response;
rootScope.UserId=response.data.UserId;
$window.sessionStorage.setItem("id",response.data.UserId);
scope.id = $window.sessionStorage.getItem("id");
state.go("userHome");
}
Thank you..!
I would create accessors on the $rootScope inside the "app.run" :
angular.module("myApp").run(['$rootScope', function($rootScope){
var id = null;
$rootScope.getId = function(){
if (!id) id = sessionStorage.getItem('id');
return id;
};
$rootScope.setId = function(userId) {
id = userId;
sessionStorage.setItem('id', userId);
};
}]);
You will simply have to use it like the following :
if(response.data.status != null)
{
scope.User=response;
rootScope.setId(response.data.UserId);
scope.id = rootScope.getId();
state.go("userHome");
}
you can simply bind it to the "controller as" provided by $rootscope :
<div>{{$root.getId()}}</div>
As far as you never have a method or property bound to a $scope
named getId
, the following will work thanks to scope inheritance (if you don't know about scope inheritance in angular, you really should spend some time googling it)
<div>{{getId()}}</div>