简体   繁体   中英

Strange array behaviour with Angular

I have a two dimensional array in controller:

var MainController = function($scope) {
    $scope.board = [[1, 2, 3, 4],
                    [5, 6, 7, 8],
                    [9, 10, 11, 12],
                    [13, 14, 15, 16]];
};

And I want to display it as table:

<table>
    <tr ng-repeat="line in board">
        <td ng-repeat="cell in line">
            {{ cell }}
        </td>
    </tr>
</table>

All work fine with this code, but if I change the data in the board to make two identical cells in the line (inner array) - this line disappear. So if I change controller to:

    $scope.board = [[1, 2, 3, 4],
                    [5, 6, 7, 7],
                    [9, 10, 11, 12],
                    [13, 14, 15, 16]];

the second line disappear.

Why and how can I fix it?

It sees the identical values as duplicates. Modify your view by adding track by syntax as follows

<table>
    <tr ng-repeat="line in board track by $index">
        <td ng-repeat="cell in line track by $index">
            {{ cell }}
        </td>
    </tr>
</table>

This

will cause the items to be keyed by their position in the array instead of their value

See Duplicate Key in Repeater

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM