【发布时间】:2013-04-12 14:28:05
【问题描述】:
我正在尝试在嵌套在 ng-repeat 指令中的 ng-repeat 指令“内”使用 ng-model。
以下 jsfiddle 演示了我的问题以及我解决该问题的两次尝试。
我的控制器定义如下:
var mod = angular.module('TestApp', []);
mod.controller('TestCtrl', function ($scope) {
var machine = {};
machine.noteMatrix = [
[false, false, false],
[false, true, false],
[false, false, false]
];
$scope.machine = machine;
// ...
});
1.
<table>
<thead>
<tr>
<th>--</th>
<th ng-repeat="no in machine.noteMatrix[0]">{{$index+1}}</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="track in machine.noteMatrix">
<td>--</td>
<td ng-repeat="step in track">
<input type="checkbox" ng-model="track[$index]"> {{step}}
</td>
</tr>
</tbody>
</table>
第一个示例/尝试更新控制器内的 machine.noteMatrix,但每次按下复选框时,angularjs 在 javascript 控制台中显示以下错误两次:
不允许在转发器中重复。中继器:步入轨道
有时它也会显示这个错误:
不允许在转发器中重复。中继器:没有在 machine.noteMatrix[0]
2.
<table>
<thead>
<tr>
<th>--</th>
<th ng-repeat="no in machine.noteMatrix[0]">{{$index+1}}</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="track in machine.noteMatrix">
<td>--</td>
<td ng-repeat="step in track">
<input type="checkbox" ng-model="step"> {{step}}
</td>
</tr>
</tbody>
</table>
第二个示例/尝试从 noteMatrix 中正确读取数据,并且在选中/取消选中复选框时,javascript 控制台中不会显示任何错误。但是,更改它们的状态不会更新控制器中的 machine.noteMatrix(按“显示矩阵”按钮以查看 jsfiddle 中的矩阵)。
有人能解释一下吗? :)
【问题讨论】:
-
使用 ng-repeat 时 $scope 属性会发生变化,因此请尝试使用 $parent.track[$index] 来访问外部范围。
-
使用 $parent.track[$index] 而不是 track[$index] 会导致相同的
Duplicates in a repeater are not allowed. Repeater: step in track错误 -
在新的角度,有两个相同的项目是错误的github.com/angular/angular.js/blob/master/CHANGELOG.md
-
好的。 angularjs 将它们报告为重复项,因为我重复原始类型并且这些是“按值传递”而不是引用。
标签: angularjs angularjs-ng-repeat