如何在本地存储中存储的对象上重复

How to ng-repeat over an object stored in Local Storage

本文关键字:存储 对象      更新时间:2023-09-26

我有一个scope函数,它返回从本地存储(使用此服务)获得的对象(JSON格式)https://github.com/grevory/angular-local-storage):

$scope.getLsKeys = function(){
    $scope.lsKeys = localStorageService.get('accountKeys');
    return $scope.lsKeys;
};

我想用一个类似于这样的ng重复来迭代返回对象的属性:

<button ng-click="console.log(key)" ng-repeat="item in getLsKeys()"></button>

问题是,由于getLsKeys/localStorageService在每个摘要周期都会返回一个新对象,Angular会对它应该监视的对象感到困惑,因为它认为自己以前从未见过这个对象(从技术上讲,这是真的)。错误消息为:

Uncaught Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations: [["fn: $watchCollectionWatch; newVal: 81; oldVal: 79"],["fn: $watchCollectionWatch; newVal: 83; oldVal: 81"],["fn: $watchCollectionWatch; newVal: 85; oldVal: 83"],["fn: $watchCollectionWatch; newVal: 87; oldVal: 85"],["fn: $watchCollectionWatch; newVal: 89; oldVal: 87"]]

所有在ng重复中使用"track by"的尝试都失败了,因为集合存储为对象,而不是数组(不幸的是,我无法更改同事的代码来进行更改)。有什么办法可以轻易地解决这个问题吗?

我想到的唯一解决方案是迭代$scope.lsKeys,并在修改本地存储时更新它,但这确实违背了Angular的全部目的。

EDIT:本地存储在应用程序运行时被修改,需要由Angular读取;也就是说,需要在运行时调用getLsKeys,而不仅仅是初始化。

您可以使用ng-init来填充范围对象:

<button ng-repeat="item in lsKeys" ng-init="lsKeys = getLsKeys()"></button>