How to track localstorage changes using AngularJS

Can $ watch be used to monitor changes in localStorage?

I have a factory to make setup / get a little easier

.factory('$localstorage', ['$window', function($window) { return { set: function(key, value) { $window.localStorage[key] = value; }, get: function(key, defaultValue) { return $window.localStorage[key] || defaultValue; }, setObject: function(key, value) { $window.localStorage[key] = JSON.stringify(value); }, getObject: function(key) { return JSON.parse($window.localStorage[key] || '{}'); } } }]); 

In my controller I have

 .controller('CodesCtrl', function($scope, $localstorage) { $scope.codes = $localstorage.getObject('codes'); ... 

In another controller, I add to local storage. I want to make changes as soon as localStorage changes.

I saw several SO posts that use things like ngStorage, but ideally I would like to avoid this.

Is it possible? Can someone point me in the right direction?

+5
source share
1 answer

You can create a $ watch function that returns everything you want. When it changes, your $ watch will work.

 $scope.$watch(function(){ return $localstorage.getObject('codes'); }, function(newCodes, oldCodes){ $scope.codes = newCodes; }); 

Be sure to do performance testing. This feature will be called a lot.


It is best to use events and update codes if necessary.

Controller A:

 var codes = updateCodesAndStoreInLocalStorage(); // <That part up to you $rootScope.$emit('codesUpdated', codes); 

Controller B:

 $rootScope.$on('codesUpdated', function(event, codes){ $scope.codes = codes; //Rely on localStorage for "storage" only, not for communication. }); 
+9
source

All Articles