angularjs 2D数组ng-repeat工作不正常

时间:2014-02-20 07:48:45

标签: javascript arrays angularjs

我在控制器中定义了一个2D数组,但是当我尝试在它上面循环时,使用2个重叠的循环,它不会像预期的那样工作。 第一个循环工作正常,但第二个循环不起作用。

JS / index.js

var gameOfLifeApp = angular.module('gameOfLifeApp', []);

gameOfLifeApp.controller('fieldCtrl', function ($scope) {
    $scope.field = [
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]
    ];
});

的index.html

<!DOCTYPE HTML>
<html ng-app="gameOfLifeApp">
<head>

    <meta charset="UTF-8">
    <title>Game of Life</title>
    <link rel="stylesheet" href="css/style.css">
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js"></script>
    <script src="js/index.js"></script>

</head>
<body ng-controller="fieldCtrl">

<div id="field">
    <div class="column" ng-repeat="column in field">
        <div class="cell" ng-repeat="cell in column"></div>
    </div>
</div>

</body>
</html>

输出:

<body ng-controller="fieldCtrl" class="ng-scope">
<div id="field">
    <!-- ngRepeat: column in field -->
    <div class="column ng-scope" ng-repeat="column in field">
        <!-- ngRepeat: cell in column -->
    </div>
    <!-- end ngRepeat: column in field -->
    <div class="column ng-scope" ng-repeat="column in field">
        <!-- ngRepeat: cell in column -->
    </div>
    <!-- end ngRepeat: column in field -->
    <div class="column ng-scope" ng-repeat="column in field">
        <!-- ngRepeat: cell in column -->
    </div>
    <!-- end ngRepeat: column in field -->
</div>
</body>

我做错了什么?

2 个答案:

答案 0 :(得分:8)

你无法使用它。如果每个单元格与非对象相同,则Angular无法跟踪每个单元格。要过度使用 track by 关键字,请使用 $index 进行跟踪。

<div id="field">
    <div class="column" ng-repeat="column in field">
        <div class="cell" ng-repeat="cell in column track by $index"></div>
    </div>
</div>

答案 1 :(得分:0)

好的,这很有趣,它在数据集中的一行重复相同的值,就像在数据集中一样:

$scope.field = [
    [0, 0, 0],
    [0, 0, 0],
    [0, 0, 0]
];

或类似地,以下数据集(以澄清我的解释,即:“行”);

$scope.field = [
    [0, 0, 0],
    [1, 1, 1],
    [2, 2, 2]
]; //notice that each "column" in a row repeats the exact same value

不允许有角度,并打破它,因此,如果你右击 - &gt;检查元素,你会得到一个错误,谈论重复。 但是,如果您更改了数据集,则对于“行”中的每个“列”,使其具有自己的值,它将按预期工作,如此;

$scope.field = [
    [1, 2, 3],
    [3, 1, 2],
    [3, 2, 1]
];

您可以在第一个答案here

中详细了解相关内容

//所以要引用该答案的相关摘录,您问题的答案是:

AngularJS不允许在ng-repeat指令中使用重复项。这意味着如果您尝试执行以下操作,则会出现错误。

// the below will throw the error Duplicates in a repeater are not allowed. Repeater: row in [1,1,1] key: number:1 <div ng-repeat="row in [1,1,1]"> 但是,稍微更改上面的代码以定义索引以确定下面的唯一性将使其再次工作。

// this will work <div ng-repeat="row in [1,1,1] track by $index">

它还有助于提及您可以应用任何自定义跟踪属性来定义唯一性,而不仅仅是$ index。因为在这种情况下,对象没有任何其他属性,这可以正常工作。发生此错误的原因是angular使用字典将项的id存储为键,并将值作为DOM引用。从代码(angular.js中的第15402行)看起来,它们基于其关键字作为性能优化来缓存先前找到的DOM元素。由于他们需要唯一键,因此当他们在第15417行找到重复键时会明确地抛出此错误

相关问题