使用AngularJS渲染带有非对象值的关联数组时遇到问题。可以使用toArray对以下数据进行排序:
{ key1: { value : data }, key2 : { value : data } }
但是如果你想对一个不包含如下对象的关联数组进行排序,那么摘要周期将继续运行,直到你得到this error
{ key1: { value : data }, key2 : { value : data } }
angular.module('app', ['angular-toArrayFilter']);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://raw.githubusercontent.com/petebacondarwin/angular-toArrayFilter/master/toArrayFilter.js"></script>
<div ng-app="app" ng-init="items = {a:'A', d:'D', c:'C', b:'B'}; items2 = {a:{value:'A'}, d:{value:'D'}, c:{value:'C'}, b:{value:'B'}}; ">
Normal iteration (unsorted - depending on browser)
<ul>
<li ng-repeat="(key, value) in items">{{ key }} = {{ value }}</li>
</ul>
Sorted iteration (sorted, but no access to key)
<ul>
<li ng-repeat="item in items | orderBy track by item">{{ $index }} = {{ item }}</li>
</ul>
Sorted iteration (works, but throws error)
<ul>
<li ng-repeat="item in items | toArray | orderBy : '$key' track by item.$key">{{ item.$key }} = {{ item.$value }}</li>
</ul>
Sorted iteration with objects (works only with objects)
<ul>
<li ng-repeat="item in items2 | toArray | orderBy : '$key' track by item.$key">{{ item.$key }} = {{ item.value }}</li>
</ul>
</div>
我使用下划线memoize
知道像https://stackoverflow.com/a/20446557/2628232这样的解决方案,但我想避免这样做。根据这里的答案,我认为这应该被报告为AngularJS的一个问题,因此可以构建一个适当的解决方案。