javascript 如何使用 AngularJS 观察本地存储的变化

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29929733/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 11:19:24  来源:igfitidea点击:

How to watch for localstorage changes with AngularJS

javascriptangularjs

提问by James J

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.

我看过一些使用 ngStorage 之类的东西的帖子,但理想情况下我想避免这种情况。

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

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

回答by HankScorpio

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 codeswhen necessary.

更好的方法是使用事件并仅codes在必要时更新。

Controller A:

控制器A:

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

Controller B:

控制器 B:

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