如何使用AngularJS观察localstorage更改

时间:2022-01-26 19:43:32

Is it possible to use $watch to monitor changes to localStorage?

是否可以使用$ watch来监控对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.

在另一个控制器中,我正在添加到本地存储。我想在localStorage更改后立即呈现更改。

I've seen a few SO posts that use things like ngStorage but ideally I'd like to avoid that.

我看过一些SO帖子使用像ngStorage这样的东西但理想情况下我想避免这样做。

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

可能吗?有人能指出我正确的方向吗?

1 个解决方案

#1


11  

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

您可以创建一个$ watch函数,返回您想要的任何内容。当它改变时,你的$ watch会运行。

$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.
});

#1


11  

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

您可以创建一个$ watch函数,返回您想要的任何内容。当它改变时,你的$ watch会运行。

$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.
});