Nested ng-repeat for multidimensional array
11,118
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
Comments
-
aurelienC almost 2 years
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]]; });
-
aurelienC about 8 yearsSo if I understand my code wasn't working because it contained only one value, and 'track by' fix this?
-
sreeramu about 8 years
track by
is added only because the array data which you are given containes same value, if your array data has different values you code will work. -
Devank about 8 yearsPlease dont use nested ng-repeat Try to make the object that ways.
-
node_man over 4 yearsthis helped me a lot
-
pdorgambide about 4 yearsIf need use ng-model on td component need use y[$index] instead of x. <td ng-repeat="x in y track by $index"><input ng-model="y[$index]" type="text"></input></td>