gpt4 book ai didi

javascript - Angular 的奇怪数组行为

转载 作者:行者123 更新时间:2023-12-02 16:46:36 24 4
gpt4 key购买 nike

我在 Controller 中有一个二维数组:

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

我想将其显示为表格:

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

使用此代码一切正常,但如果我更改板上的数据以在该行(内部数组)中创建两个相同的单元格 - 该行就会消失。因此,如果我将 Controller 更改为:

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

第二行消失。

为什么以及如何解决它?

最佳答案

它将相同的值视为重复项。通过添加 track by 语法来修改您的 View ,如下所示

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

这个

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

参见Duplicate Key in Repeater

关于javascript - Angular 的奇怪数组行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27069832/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com