问题描述
我正在尝试使用ng-repeat指令在html中显示二维数组.我可以显示第一个维度(表行),但第二个维度(表数据)不起作用.我已经看到了许多使用对象,JSON,键值数据结构的解决方案...但是我找不到仅适用于包含其他数组的数组的某些解决方案.这是一些失败的尝试.
HTML:(无效)
I am trying to display a bi-dimensional array in html using the ng-repeat directive. I can display the first dimension ( table rows) but the second (table datas) is not working. I have seen a lot of solutions using objects, JSON, key-values data structures... But I can't find something that work for just an array containing others arrays. Here are some unsuccessful attempts.
HTML: (does't work)
<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
由于您的数组数据包含重复项,因此您想添加track by
作为唯一ID,因此我已经添加了track by $index
关于此 https://docs.angularjs.org/error/ngRepeat/dupes
As your array data contains duplicate you want to add track by
for unique id so i had added track by $index
more about this https://docs.angularjs.org/error/ngRepeat/dupes
这篇关于嵌套ng-repeat用于多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!