gpt4 book ai didi

javascript - AngularJS- "Duplicates in a repeater not allowed"

转载 作者:行者123 更新时间:2023-11-30 08:43:47 31 4
gpt4 key购买 nike

我正在尝试为数组的每个成员创建一个 HTML textarea,但它没有呈现。我已阅读 AngularJS 文档并尝试了各种 track by 表达式但无济于事。

如果用户在多个 textareas 中输入相同的文本,则会出现错误情况。看起来 Angular 正在使用文本区域的值作为唯一键。我可以通过在文本之前添加和删除任意标识符来解决这个问题,但这看起来很蹩脚。

需要明确的是,文本区域显示的问题是在用户单击提交之后(仅限 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?"
]

最佳答案

更改或添加 track by 部分到您的 ng-repeat

使用 by $indexby openEndedQuestion

 <tr ng-repeat="oeq in openEndedQuestions track by oeq">

 <tr ng-repeat="oeq in openEndedQuestions track by $index">

最好使用第二种情况

同样作为一般规则,尽量不要绑定(bind)到 Angular 图元(即字符串和数字)。更好的解决方案可能是:

在 Controller 中:

$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/

关于javascript - AngularJS- "Duplicates in a repeater not allowed",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23811250/

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