Olivier Grech Olivier Grech - 5 months ago 45
AngularJS Question

AngularJS - Displaying a grid with ng-repeat

I want to draw a grid of canvas element. Each element of the grid has a color attribute and an id. This is how I create the two-dimensions array :

$scope.hexGrid = new Array();
for (var i = 0 ; i < GRIDSIZE ; i++) {
$scope.hexGrid[i] = new Array();
}

for (var i = 0 ; i < GRIDSIZE ; i++) {
for (var j = 0 ; j < GRIDSIZE ; j++) {
var hex = {color: "green", id: i * GRIDSIZE + j};
$scope.hexGrid[i].push(hex);
}
}


Now here's my question. How would I display a grid using ng-repeat and this two-dimensions array? Should I nest 2 ng-repeat (one for the columns, one for the rows)?

<span ng-repeat="hex in hexGrid[1] track by hex.id">
<canvas id="myCanvas" width="100" height="100" style="border:1px solid #000000;"></canvas>
</span>


The first ng-repeat works well for a fixed row, but how should I make the second ng-repeat?

(and finally, is this even a good method?)

Answer

Yes, you should nest ng-repeats. Also, I'd suggest you to use class="myCanvas" instead of id for obvious html tagging reasons.

<span ng-repeat="arr in hexGrid">
    <span ng-repeat="hex in arr track by hex.id">
        <canvas id="myCanvas" width="100" height="100" style="border:1px solid #000000;"></canvas>
    </span>
</span>