AngularJS中使用ng-repeat解析嵌套JSON对象数组并渲染表格
嘿,我来帮你搞定AngularJS里用ng-repeat渲染嵌套JSON数组成表格的问题!首先得先明确你的嵌套JSON结构,不过我先拿两种最常见的场景来演示,你可以对着自己的数据调整。
场景1:数据是「表头数组 + 行数据数组」的嵌套结构
假设你的JSON长这样——表头存在一个数组里,每个元素的name字段就是表头文字,行数据是另一个数组,每行是对应表头的键值对:
// 在你的AngularJS控制器里定义数据 app.controller('TableCtrl', function($scope) { $scope.tableInfo = { // 表头数组,每个元素的name是表头文本,key用来对应行数据的字段 columns: [ { name: "用户名", key: "username" }, { name: "邮箱", key: "email" }, { name: "注册时间", key: "registerDate" } ], // 行数据数组 rows: [ { username: "Alice", email: "alice@example.com", registerDate: "2023-01-01" }, { username: "Bob", email: "bob@example.com", registerDate: "2023-02-15" } ] }; });
然后HTML里这么写,用ng-repeat分别渲染表头和单元格:
<div ng-controller="TableCtrl"> <table border="1"> <thead> <tr> <!-- 遍历表头数组,取name作为表头文字 --> <th ng-repeat="col in tableInfo.columns">{{ col.name }}</th> </tr> </thead> <tbody> <!-- 遍历每行数据 --> <tr ng-repeat="row in tableInfo.rows"> <!-- 遍历表头,用col.key匹配行数据的字段 --> <td ng-repeat="col in tableInfo.columns">{{ row[col.key] }}</td> </tr> </tbody> </table> </div>
场景2:数据是「列优先」的嵌套数组(每个对象存表头+对应列的所有值)
如果你的JSON是列优先的(比如每个对象代表一列,包含name和该列的所有值),像这样:
app.controller('TableCtrl', function($scope) { $scope.columnData = [ { name: "姓名", values: ["张三", "李四", "王五"] }, { name: "年龄", values: [25, 30, 28] }, { name: "职业", values: ["前端开发", "UI设计", "产品经理"] } ]; // 先把列优先的数据转成行优先的格式,方便表格渲染 $scope.headers = $scope.columnData.map(col => col.name); // 提取表头 $scope.rowData = []; const rowCount = $scope.columnData[0].values.length; // 获取行数 for (let i = 0; i < rowCount; i++) { const row = {}; $scope.columnData.forEach(col => { row[col.name] = col.values[i]; }); $scope.rowData.push(row); } });
对应的HTML就简单了,直接遍历表头和行数据:
<div ng-controller="TableCtrl"> <table border="1"> <thead> <tr> <th ng-repeat="header in headers">{{ header }}</th> </tr> </thead> <tbody> <tr ng-repeat="row in rowData"> <td ng-repeat="header in headers">{{ row[header] }}</td> </tr> </tbody> </table> </div>
一些实用小Tips
- 如果你的行数据是纯数组(比如
rows: [["Alice", "alice@example.com", ...], ...]),那单元格可以直接用row[$index]来匹配表头的顺序 - 如果数据里有重复项或者触发ng-repeat的重复报错,可以加上
track by $index,比如ng-repeat="col in tableInfo.columns track by $index" - 如果需要处理空值,可以用AngularJS的默认值语法,比如
{{ row[col.key] || '-' }}来显示占位符
内容的提问来源于stack exchange,提问作者sai123
相关产品推荐
相关产品推荐

