Search code examples
javascriptangularjslocal-storagesession-storage

Get sessionStorage and restore value


I have an angular application with different view. On a first view I create a variable and on the second view I have to edit it. I use for this "sessionStorage". On the first view, I record list of variable on $sessionStorage when I go to another page.

I get this data when I start second view. On this view, I want be able to edit value or not. When I click on valid button, I record the new value and when I press cancel button, I get initial value.

This is the js file of the second view.

angular.module('testNgStorageApp')
  .controller('MainCtrl', function ($scope, $sessionStorage) {
    var listNameRecorded = $sessionStorage.namesRecord;
    $scope.listNameTemp = listNameRecorded || [];

    $scope.edit = function(index){
        console.log("before", $scope.listNameTemp, listNameRecorded, $sessionStorage.namesRecord)
        $scope.listNameTemp[index] = $scope.newText;
        console.log("after", $scope.listNameTemp, listNameRecorded, $sessionStorage.namesRecord)
    }
...
});

html

<div ng-repeat="name in listNameTemp">
    <span>{{name}}</span>
    <input ng-model="newText"/>
    <button ng-click="edit($index)">Edit</button>
  </div>

My problem is when I edit the value ($scope.listNameTemp), $sessionStorage.namesRecords is automatically modify.


Solution

  • The reason why $sessionStorage.namesRecords is getting modifying is that the reference of $sessionStorage.namesRecords was assigned to $scope.listNameTemp.

    You can use angular.copy() to void this problem. angular.copy() create and returns a whole new copy of the object passed to it.

    Updated Code:

    angular.module('testNgStorageApp')
      .controller('MainCtrl', function ($scope, $sessionStorage) {
        var listNameRecorded = angular.copy($sessionStorage.namesRecord);
        $scope.listNameTemp = listNameRecorded || [];
    
        $scope.edit = function(index){
            console.log("before", $scope.listNameTemp, listNameRecorded, $sessionStorage.namesRecord)
            $scope.listNameTemp[index] = $scope.newText;
            console.log("after", $scope.listNameTemp, listNameRecorded, $sessionStorage.namesRecord)
        }
    ...
    });