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

标签 javascript angularjs angularjs-ng-repeat

我正在尝试为数组的每个成员创建一个 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/

相关文章:

javascript - 将序列化数据转换为数组或对象

javascript - 在 ES6 + Angular 1.4 指令中插入

javascript - 检查 json 对象是否存在并保存到本地存储中

javascript - 在 Angularjs 应用程序中使用 AND 操作过滤基于 ng 重复的多个属性

javascript - 当父项被过滤时,输入会丢失其值

javascript - 以 this 作为参数的复选框开关不会保存更改 .checked 值

javascript - 无法读取reducer redux中未定义的属性 'data'

javascript - JQuery:如何在发送表单之前执行代码

javascript - angularjs监听dom事件

javascript - 为什么 Angular 无法获取输入的 ng-models 值,$sce.trustAsHtml 插入的 html?