嵌套的ng-repeat用于多维数组

时间:2016-04-17 16:10:15

标签: javascript arrays angularjs multidimensional-array

我正在尝试使用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]];
});

1 个答案:

答案 0 :(得分:6)

工作示例:

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的更多信息