Search code examples
javascriptangularjsangularjs-service

How to change stored value in Value recipe of angular


From the angular documentation, I can see that a value recipe can be used to store some information that can be injected in different modules. So I wanted to use this for storing some user related configurations in my angular app.

What I am doing right now:

Set a value by default-

app.value('display', {
        header: true,
        switcher: true
    })

I have a header and switcher in my views that I want to show or hide based on the value of header and switcher coming from above assignment.

This part of display and hiding works fine. What I want is that if some controller changes the value of header to false, header should then be hidden for that particular user. So from within my controller I just set the values to false. But on page refresh, these values are gone.

I am not sure what is going wrong here. Are we not supposed to change the value? If not, isn't that just a constant. In case we are not supposed to update values, what would be a better way to store some user related variables that will be available to entire app.


Solution

  • First make a factory like

    (function() {
    "use strict";
    angular.module('dataModule',[])
    .factory('datafactory',function(){
    return {
    
    };
    });
    })();
    

    Now datafactory can be accessed any where in application just you need to inject this module in required module and factory in required controller

    use like this

    datafactory.myReusableVar  ="something"
    

    later on in someother controller

    $scope.myLocalVar =datafactory.myReusableVar
    
    //using session storage
    var x ="value"// x can be any data type string,array, or object
    sessionStorage.setItem("mySessionItem",x)
    $scope.mysessionValue =sessionStorage.getItem("mySessionItem")