多维数组的嵌套ng重复

Nested ng-repeat for multidimensional array

本文关键字:ng 重复 嵌套 数组      更新时间:2023-09-26

我正在尝试使用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 $indexhttps://docs.angularjs.org/error/ngRepeat/dupes