Tourshi Tourshi - 6 months ago 34
AngularJS Question

Angularjs sessionStorage and scope

Anyone know why my scope variables aren't being updated? It's mind boggling to me. The sessionStorage variables are fine but when I define them within scope variables.. I get 'undefined' errors. I've tinkered with $scope.$apply but apparently the scope is already being digested...:S please help a newbie out.

if(sessionStorage.loggedIn){

$scope.user = sessionStorage.user;
$scope.user.gravatar = sessionStorage.gravatar;
console.log($scope.user.gravatar);
console.log('Session variable is active');
$scope.loggedIn = sessionStorage.loggedIn;

}


the full code:

app.controller('loginCtrl', ['$scope','$route','Auth','$modal','$timeout', function($scope,$route,Auth,$modal,$timeout){

if(sessionStorage.loggedIn){

$scope.user = sessionStorage.user;
$scope.user.gravatar = sessionStorage.gravatar;
console.log($scope.user.gravatar);
console.log('Session variable is active');
$scope.loggedIn = sessionStorage.loggedIn;

}

$scope.login = function(){
Auth.save({
'username': $scope.username,
'password': $scope.password
},function(data) {
$scope.loggedIn = true;
$scope.user = data.user;
$scope.user.gravatar = data.gravatar;

sessionStorage.loggedIn = $scope.loggedIn;
sessionStorage.user = data.user;
sessionStorage.gravatar = data.gravatar;
$route.reload();

},function(response){
$scope.flash = response.data.flash;
$scope.pop = true;
$timeout(function(){$scope.pop = false;}, 3000);
})

};

$scope.logout = function (){
Auth.get({},function(){
delete sessionStorage.user;
delete sessionStorage.gravatar;
delete sessionStorage.loggedIn;
$scope.loggedIn = false;
$timeout(function(){$route.reload();}, 1000);
})
};


}]);


Summary of chain of events:

1) User logs in

2) Upon successful login, the user's details (json object) are stored in
sessionStorage.user = data.user
and the data.user variable typically contains this sort of info
{id: 1, username: "user123", firstname: "", lastname: "", email: "username@gmail.com"}

-the user's gravatar hash is also stored in a sessionStorage.user.gravatar variable.

3) If user logs out, sessionStorage variables are deleted.

4) However, if user is still logged in, refreshes/reloads the page (from browser), the sessionStorage variable is still active, and still contains the data, BUT for some reason, when I set scope variables eg.
$scope.user = sessionStorage.user
--the scope variable remains undefined--despite sessionStorage.user being perfectly viable. The issue appears to be with the scope.

Answer

You need to serialize your user object to JSON before storing on sessionStorage, because it is implemented as a collection of string values.

Try something like this

 sessionStorage.user = JSON.stringify($scope.user);

and then

 $scope.user = JSON.parse(sessionStorage.user);