AngularJS嵌套ng-repeat中orderBy排序失效问题求助
我来帮你排查这个嵌套ng-repeat排序失效的问题,主要有两个核心原因,咱们一步步拆解解决:
1. 外层排序失效:orderBy无法作用于对象
你的$scope.resumenesRondaInventariosPorTienda是一个对象(键为"0"、"1"的键值对结构),但AngularJS的orderBy过滤器仅支持对数组进行排序——直接对对象使用orderBy完全不会生效,因为JS对象的属性遍历顺序本身就不确定,且orderBy没有处理对象的逻辑。
解决办法:先把对象转换成数组
在控制器里,我们需要把这个对象转换成数组,才能正常使用orderBy。如果不需要保留原对象的键,直接提取值即可:
// 把对象的值提取为数组 $scope.resumenesArray = Object.values($scope.resumenesRondaInventariosPorTienda);
如果你的AngularJS版本较旧(不支持Object.values()),可以用兼容写法:
$scope.resumenesArray = []; Object.keys($scope.resumenesRondaInventariosPorTienda).forEach(key => { $scope.resumenesArray.push($scope.resumenesRondaInventariosPorTienda[key]); });
然后修改外层ng-repeat,使用转换后的数组,并指定正确的排序字段(因为每个数组元素是[[{...}]]结构,要取内层的ID_CO):
<article class="unaTienda" ng-repeat="tienda in resumenesArray | orderBy:'[0][0].ID_CO'">
2. 内层排序未生效:遍历目标错误+未添加orderBy
你的内层ng-repeat写的是documento in tienda[$index],这里的$index是外层循环的索引,属于逻辑错误:比如外层第一个tienda是[[{...}, {...}]],$index为0时刚好能取到正确的数组,但这只是巧合,正确的遍历目标应该是tienda[0](因为每个tienda元素是二维数组,第一层只有一个元素)。
另外,你没有给内层添加orderBy过滤器,所以内层数据自然不会排序。
解决办法:修正遍历目标并添加内层排序
假设你想按numeroDocumento排序内层文档,修改内层ng-repeat如下:
<article class="unDocumento" ng-repeat="documento in tienda[0] | orderBy:'numeroDocumento'">
如果要按日期反向排序,就换成orderBy:'-fechaDocumento',根据你的需求调整即可。
完整修改后的代码
控制器部分
// 转换对象为数组 $scope.resumenesArray = Object.values($scope.resumenesRondaInventariosPorTienda);
视图部分
<article class="unaTienda" ng-repeat="tienda in resumenesArray | orderBy:'[0][0].ID_CO'"> <h3 class='bold'>{{tienda[0][0].nombreTienda}}</h3> <article class="unDocumento" ng-repeat="documento in tienda[0] | orderBy:'numeroDocumento'"> <h3>{{documento.tipoDocumento}} {{documento.numeroDocumento}}</h3> </article> </article>
内容的提问来源于stack exchange,提问作者quelquecosa

