Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested ng-repeat for multidimensional array

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: (doesn't work)

<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]];
});
like image 878
aurelienC Avatar asked Apr 17 '16 16:04

aurelienC


1 Answers

Working example:

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="[email protected]" 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"]];
});

demo: http://plnkr.co/edit/yVC5nrH5Pv3Zzp8Py7FH?p=preview

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

like image 155
sreeramu Avatar answered Sep 20 '22 02:09

sreeramu