Is it possible to use $watch to monitor changes to localStorage?
I have a factory to make setting/getting a little simpler
.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'm adding to local storage. I'd like to render the changes as soon as localStorage changes.
I've seen a few SO posts that use things like ngStorage but ideally I'd like to avoid that.
Is it possible? Could someone point me in the right direction?
Save the Angular app and run the application. After the app gets loaded, type in localStorage from the browser console and you will be able to see the encrypted data in local storage. While trying to access the local storage data inside the application, you can get the decrypted data.
# View localStorage keys and valuesClick the Application tab to open the Application panel. Expand the Local Storage menu. Click a domain to view its key-value pairs. Click a row of the table to view the value in the viewer below the table.
localStorage and sessionStorage are almost identical and have the same API. The difference is that with sessionStorage , the data is persisted only until the window or tab is closed. With localStorage , the data is persisted until the user manually clears the browser cache or until your web app clears the data.
You can create a $watch function that returns anything you want. When it changes, your $watch will run.
$scope.$watch(function(){
return $localstorage.getObject('codes');
}, function(newCodes, oldCodes){
$scope.codes = newCodes;
});
Make sure to do performance testing on that. This function will be called a lot.
A better way would be to use events and only update codes
when necessary.
Controller A:
var codes = updateCodesAndStoreInLocalStorage(); // <That part's 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.
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With