我正在尝试为数组的每个成员创建一个HTML textarea
,但它不会呈现。我已经阅读了AngularJS文档并尝试了各种track by
表达式无济于事。
如果用户在多个textareas
中输入相同的文本,则会出现错误情况。似乎Angular正在使用文本区域的值作为唯一键。我可以通过在文本之前添加和删除任意标识符来破解这一点,但这似乎很蹩脚。
要清楚textareas显示问题是在用户点击提交后(仅限javascript - 没有往返服务器),然后后续代码呈现用户键入的内容。
由于式提前。
我得到的具体错误是:
Duplicates in a repeater are not allowed.
Use 'track by' expression to specify unique keys.
Repeater: openEndedQuestion in openEndedQuestions track by openEndedQuestion.id,
Duplicate key: undefined
HTML是:
<tr ng-repeat="openEndedQuestion in openEndedQuestions">
<td width="375" style="font-size: 18px;">
<b>{{openEndedQuestion}}</b><br>
<textarea id="openEndedAnswer_{{$index}}" cols="80"></textarea>
</td>
</tr>
第二阶段HTML是:
<tr ng-repeat="openEndedAnswer in openEndedAnswers">
<td width="375" style="font-size: 18px;">
<b>{{openEndedAnswer}}</b>
</td>
<td width="225">
<span style="font-size: 35px; padding: 2px; color: #468847;"
ng-repeat="starIndex in [0, 1, 2, 3, 4]"
ng-click="povStarTracker.setStarRating($parent.$index, starIndex + 1)"
ng-class="povStarTracker.getClassForStar($parent.$index, starIndex)"></span>
</td>
</tr>
基础JSON是:
"openEndedQuestions" : [
"Do you think the coach is being fair?",
"Should the coach give all of his players a chance to play in the games?",
"Should Austin say anything about this to his coach?",
"What could Ryan say to Austin?"
]
答案 0 :(得分:5)
将track by
部分更改或添加到ng-repeat
使用by $index
或by openEndedQuestion
<tr ng-repeat="oeq in openEndedQuestions track by oeq">
或
<tr ng-repeat="oeq in openEndedQuestions track by $index">
最好使用第二种情况
同样作为一般规则,尽量不要以角度(即字符串和数字)绑定到基元。更好的解决方案可能是:
在控制器中:
$scope.questions = [
{id:1, text: "Do you think the coach is being fair?"},
{id:2, text: "Should the coach give all of his players a chance to play in the games?"},
{id:3, text: "Should Austin say anything about this to his coach?"},
{id:4, text: "What could Ryan say to Austin?"}
]
并在模板中:
<tr ng-repeat="q in questions track by q.id">
参见jsfiddle:http://jsfiddle.net/vittore/V5n4t/