我正在尝试使用 ng-repeat 指令在 html 中显示二维数组。我可以显示第一个维度(表格行),但第二个维度(表格数据)不起作用。我见过很多使用对象、JSON、键值数据结构的解决方案……但我找不到仅适用于包含其他数组的数组的方法。以下是一些不成功的尝试。
HTML:(无效)
<div ng-app = "grid" ng-controller = "gridCtrl">
<table>
<tr ng-repeat = "y in grid">
<td ng-repeat = "x in y"></td>
</tr>
</table>
</div>
HTML:(不起作用)
<div ng-app = "grid" ng-controller = "gridCtrl">
<table>
<tr ng-repeat = "y in grid">
<td ng-repeat = "x in grid[$index]"></td>
</tr>
</table>
</div>
JS:
var grid = angular.module("grid", []);
grid.controller("gridCtrl", function($scope)
{
$scope.grid = [[empty, empty, empty, empty, empty],
[empty, empty, empty, empty, empty],
[empty, empty, empty, empty, empty],
[empty, empty, empty, empty, empty],
[empty, empty, empty, empty, empty]];
});
最佳答案
工作示例:
HTML:
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>
document.write('<base href="' + document.location + '" />');
</script>
<script data-require="angular.js@1.4.x" src="https://code.angularjs.org/1.4.9/angular.js" data-semver="1.4.9"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
<div>
<table>
<tr ng-repeat="y in grid">
<td ng-repeat="x in y track by $index">{{x}}</td>
</tr>
</table>
</div>
</body>
</html>
JS:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
$scope.grid = [["empty", "empty", "empt", "empt", "empty"],
["empty", "empty", "empt", "empt", "empty"]];
});
演示:http://plnkr.co/edit/yVC5nrH5Pv3Zzp8Py7FH?p=preview
由于您的数组数据包含重复项,因此您想为唯一 ID 添加 track by
,所以我添加了 track by $index
更多关于此 https://docs.angularjs.org/error/ngRepeat/dupes
关于javascript - 多维数组的嵌套 ng-repeat,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36678928/