angularjssessionstorageng-storage

How to store a JSON Variable with AngularJS ngStorage to $sessionStorage


I have the following variable which is easily transformed to a JSON-String:

var data = {
    ball: {
        colour: "",
        size: "",
        price: ""
    },
    toys: []
}

In my Controller I want add this variable to the scope like:

$scope.data = angular.copy(data)

Then I want it to store on the $sessionStorage like:

$sessionStorage.data = angular.toJson($scope.data);

After the page refresh the $scope.data is empty again. Any ideas?


Solution

  • This is how my code works:

        $scope.$storage = $sessionStorage;
    
        if (typeof $scope.$storage.data !== 'undefined') {
            $scope.data = $scope.$storage.data;
        } else {
            $scope.data = angular.copy(data);
            $scope.$storage.data = $scope.data;
        }
    

    A shorter solution would be:

        $scope.cv = $scope.$storage.cv || angular.copy(cv);
        $scope.$storage.cv = $scope.cv;