AngularJS遍历键值对对象:视图渲染问题求助
解决AngularJS分组渲染API响应的问题
问题背景
从REST API获取到如下格式的响应数据,需要按分组(对应"0"、"1"这类键)展示:每组左侧显示分组编号,右侧列出该组内所有物品的描述和颜色。
const response = { "0": [ { "description": "basket", "color": "red" }, { "description": "pillow", "color": "blue" }, { "description": "armchair", "color": "white" } ], "1": [ { "description": "shirt", "color": "black" }, { "description": "pants", "color": "blue" } ] };
原controller和view代码无法实现预期效果:
// controller.js self.catKeys= Object.keys(response) self.catValue= Object.values(response)
<!-- view.html --> <div ng-repeat="cat in ctrl.catKeys" class="col-md-3"> {{ cat }} </div> <div ng-repeat="val in ctrl.catValue" class="col-md-9"> {{ val[index].description }} {{ val[index].color}} </div>
问题分析
- 分开遍历
catKeys和catValue会导致两组ng-repeat独立执行,无法将分组键和对应值关联到同一行。 val[index]中的index未定义,无法遍历每个分组下的物品列表。
解决方案
方案1:优化Controller结构(推荐)
将响应数据转换为包含分组ID和对应物品的数组,让视图更易处理:
// controller.js self.groupedItems = Object.entries(response).map(([groupId, items]) => ({ groupId: groupId, items: items }));
视图中嵌套ng-repeat实现分组渲染:
<!-- view.html --> <div class="row" ng-repeat="group in ctrl.groupedItems"> <!-- 左侧分组编号 --> <div class="col-md-3">{{ group.groupId }}</div> <!-- 右侧物品列表 --> <div class="col-md-9"> <div ng-repeat="item in group.items"> {{ item.description }} ({{ item.color }}) </div> </div> </div>
方案2:直接在视图中遍历键值对
无需修改Controller,直接使用AngularJS的(key, value) in object语法遍历响应对象:
<!-- view.html --> <div class="row" ng-repeat="(groupId, items) in ctrl.response"> <div class="col-md-3">{{ groupId }}</div> <div class="col-md-9"> <div ng-repeat="item in items"> {{ item.description }} - {{ item.color }} </div> </div> </div>
这两种方案都能实现分组展示的效果:每个分组占一行,左侧显示分组ID,右侧列出该组所有物品的详细信息。
内容的提问来源于stack exchange,提问作者LaraGrimci
相关产品推荐
相关产品推荐

