Iker Aguayo Iker Aguayo - 1 year ago 60
HTML Question

Access $window.sessionStorage from html

In my case I am working with angularjs and I want to access a saved value in user to show or not some html tags.

First it save in some controller the user variable, it is a part of log in action.

$window.sessionStorage.setItem('user', AuthenticationService.getUser());

Then, I want to show some html tags depending on the role of that user, with something like the following:

<li><a id="id" ng-if="user.role=='admin'" href> console </a></li>

I had something similar to this using $rootScope, but when I refresh the page I lose the value. That is why I need to use window.sessionStorage

Is there any way to access in html a saved value in sessionStorage? or this is wrong and I need another approach?


$window is just a wrapper around window, so this approach will work, but it's more preferable to use some other means, such as cookies than to pollute $window.

You should use a controller function or even better, a global user service to access the user.

There's a pretty detailed article on how to do this here: http://www.nesterovsky-bros.com/weblog/2015/01/26/windowsessionStorageInAngularJS.aspx

If you have multiple user properties, use toJson and fromJson to store the object in session storage such as:

var user = { name:'mike', role: 'admin'}


var user = angular.fromJson($window.sessionStorage.getItem('user'))

If you need to access the user from a number of different places, a service like @Deblaton recommended is the way to go, but assuming you have multiple properties on your user, add the angular.toJson and angular.fromJson lines like I have above.

The way you are accessing the user in your html requires that it's present on the current scope so if you use the service approach in your controller you would add:

$scope.user = UserService.getUser();