siva siva - 3 years ago 158
AngularJS Question

How to access angularjs sessionStorage value to entire project?

i need login values entire i'm using rootScope. but my page is refresh rootScope value destroyed.
so instead of rootScope i'm using angularjs sessionStorage.value is set successfully. now i need to use sessionStorage value in entire project.

how to use sessionStorage value in where ever i want.looking positive replay


if( != null)
$window.sessionStorage.setItem("id",; = $window.sessionStorage.getItem("id");

Thank you..!

Answer Source

I would create accessors on the $rootScope inside the "" :

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);

  • That way, you can keep on using your id inside views, you will just have to make a call.
  • You won't forget to check sessionStorage if the $rootScope has no value set.
  • You won't have to access sessionStorage every time you need the id (querrying the session storage is way slower than getting an item on the heap)

You will simply have to use it like the following :

if( != null)
    rootScope.setId(; = rootScope.getId();

For accessing it into your views :

version 1.5+ :

you can simply bind it to the "controller as" provided by $rootscope :


version 1.5- :

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)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download