Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular js watch session Storage

I have some data from different controllers that are stored in the sessionStorga using https://github.com/fredricrylander/angular-webstorage. The data is stored ok and it's available in the current session. The problem I am facing regards making a controller that will watch for changes in the webstorage.session I did this like this:

app.controller(
    'updateDataController',
    ['$scope','$http','$sce','$location','$routeParams', '$rootScope', '$document', 'webStorage', '$interval', 'md5',
        function($scope,$http,$sce,$location,$routeParams, $rootScope, $document, webStorage, $interval, md5) {

            $scope.mySessionStorage = webStorage.session;

            $scope.$watch('mySessionStorage', function (newVal, oldVal) {
                 console.log("The web storage has changed");
            }, true);

        }
    ]);

I get the console.log output only once. I don't get any logs even though I change the content of webStorage.session. What could be the problem?

like image 999
exilonX Avatar asked Sep 29 '22 18:09

exilonX


1 Answers

webStorage.session is only setting the value to $scope.mySessionStorage one time upon the initialization of your controller. So that code above the watch is only firing one time.

Try watching the webStorage.session value instead of the value in the controller:

$scope.$watch(function () {
   return webStorage.session;
}, function (newVal, oldVal) {
   console.log("The web storage has changed");
}, true);
like image 97
sma Avatar answered Oct 03 '22 00:10

sma