user2465164
user2465164

Reputation: 937

Accessing 2D Arrays in AngularJS

I've searched around a bit and found a number of similar things, but none that seem to answer my problem:

I'm creating a spreadsheet with AngularJS, which I have done based on this tutorial, from there I have been attempting to alter the code to fit my needs.

I am trying to fill the cells with different values that I have in a 2D array like so:

[
    ["block A1", "block B1", "block C1"],
    ["block A2", "block B2", "block C2"]
]

I would like for these strings to fill in their respective cell via the <input value=""> tag. How would I go about using ng-repeat (or anything else applicable) to access inner elements of a 2D array?

Here is my current code:

sheet= function($scope, $parse){
    $scope.columns = headerRow2;
    $scope.rows = numOfRows;
    $scope.cells = {};
    $scope.values = filteredResults;

    //... 
}


<div ng-app ng-controller="sheet">
    <table>
        <tr class="column-label">
            <td></td>
            <td ng-repeat="column in columns">{{column}}</td>
        </tr>
      <tr ng-repeat="row in rows">
            <td class="row-label">{{row}}</td>
            <td ng-repeat="column in columns">
                <div>
                    <input ng-repeat="subvalues in values[$index]" value="{{subvalues}}">
                </div>
            </td>
        </tr>
    </table>
</div>

I'm looking for an inline double-for-loop type deal.

Edit: I just tried what flim suggested, and while it's what I need regarding the double-for-loop, each of my input boxes only hold the value of block C2 (the last index in the last array). Since my input boxes are confined to be inside the <td> tags, I'm under the impression that the repeat is working, however it's repeating it each time inside the same <td>, causing it to override itself and work to the end until it moves on to the next <td> block. Any clue how to stop this? It looks like it's just a matter of where I place the repeat functions, but that almost brings me back to my first issue.

Upvotes: 0

Views: 2976

Answers (1)

Foo L
Foo L

Reputation: 11137

Here's some code I threw together for a real quick test:

In the controller, I have

$scope.tempArr = [
  ["block A1", "block B1", "block C1"],
  ["block A2", "block B2", "block C2"]
];

In my html, I have:

<span ng-repeat="row in tempArr">
  <span ng-repeat="cell in row">
    <input type="text" value="{{cell}}">
  </span>
</span>

Extrapolate for your own formatting.

Here's the jsfiddle. And another with the table.

Upvotes: 1

Related Questions