Search code examples
angularjswatchsession-storage

Data strangely synchronized between viewmodel and $sessionStorage


I am storing a list of objects in the $sessionStorage. Then in one of my controllers I get the value of that list and display it on the page and the user can delete its items.

The problem is, that when the user deletes one item of that list from the view model, it gets also deleted from the $sessionStorage which I don't want.

Here is my controller's code

(function () {
  'use strict';

  myModule.controller('infoCollecteArticlesController', ['$scope', '$rootScope', '$location', '$sessionStorage', 'global_factory', 'infoCollecteArticlesFactory',
  function ($scope, $rootScope, $location, $sessionStorage, global_factory, infoCollecteArticlesFactory) {
    var vm = this;

    /*
    * PUBLIC FUNCTIONS
    */

    // Delete a URL from the vm
    vm.deleteUrl = function(index) {
        vm.web_urls.splice(index, 1);
    }

    // Watch sessionStorage
    $scope.$watch(function () {
        return $sessionStorage.currentCommuneData;
    }, function (newVal, oldVal) {
        if (newVal) {
            vm.web_urls = newVal.web_information.web_urls;
            vm.filters = newVal.web_information.stop_list;
        }
        else {
            window.location.replace("test.html");
        }
    }, true);
}
]);
})();

Solution

  • vm.web_urls = newVal.web_information.web_urls;

    This line directly refer to the object of the sessionStorage variable with the same memory location.

    So, even of you remove the object from vm.web_urls, the data from sessionStorage is getting deleted.

    Instead copy the object but not reference using

    vm.web_urls = angular.copy(newVal.web_information.web_urls);
    vm.filters = angular.copy(newVal.web_information.stop_list);
    

    So change your watch function to,

    $scope.$watch(function () {
            return $sessionStorage.currentCommuneData;
        }, function (newVal, oldVal) {
            if (newVal) {
                vm.web_urls = angular.copy(newVal.web_information.web_urls);
                vm.filters = angular.copy(newVal.web_information.stop_list);
            }
            else {
                window.location.replace("test.html");
            }
        }, true);