ng-repeat 不使用 track by 更新模型 [英] ng-repeat not update model with track by

查看:23
本文介绍了ng-repeat 不使用 track by 更新模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用 checklist-model 来处理一系列复选框,每个选中的复选框都可以删除.一切似乎都很好,直到我在 ng-repeat 中使用它.

I've been using checklist-model to work with an array of check-boxes with each selected one can be deleted. Everything seems to work fine until I use it inside a ng-repeat.

问题是,当我添加 track by $indexng-repeat 时,已删除的复选框仍然存在.如果我删除那个 track by,它工作正常(但在我的真实应用中,我需要 track by 才能工作).

The problem is, the deleted check-boxes still be there around when I add the track by $index along with the ng-repeat. If I remove that track by, it works fine (but in my real app I need that track by to work).

这是一个 plnkr,演示

Here's a plnkr, Demo

要查看问题,您可以按照以下步骤操作.

To see the problem, you can follow these steps.

  1. 选择您想要的任何复选框
  2. 删除那些选定的
  3. 选中检查所有按钮以查看,

现在看看带有 track by 的那个,它会留下一些未选中的复选框.如果您手动检查它,它会将旧值添加到列表中.这很奇怪.

Now look at the one with track by, it will leave some check-box unchecked. If you check it manually, it will have the old value added to the list. This is weird.

任何帮助或解释将不胜感激,谢谢

Any help or explaination will be really appreciate, thanks

推荐答案

如果你仍然需要跟踪,使用它和对象的 id.假设对象的 id 将始终是唯一的.

If you still need to track by, use it with the id of the object. Assuming the id of the object will be always unique.

将多个跟踪函数解析为同一个键是错误的.(这意味着两个不同的对象被映射到同一个 DOM 元素,这是不可能的.)

It is an error to have more than one tracking function to resolve to the same key. (This would mean that two distinct objects are mapped to the same DOM element, which is not possible.)

所以不是这样:

<tr ng-repeat="verb in verbs track by $index">
    <td>
      <input type="checkbox" checklist-model="list.verbs" checklist-value="verb.id">
    </td>
    <td>
      {{verb.id}}
    </td>
    <td>
      <span>{{verb.text}}</span>
    </td>
  </tr>

使用这个:

  <tr ng-repeat="verb in verbs track by verb.id">
    <td>
      <input type="checkbox" checklist-model="list.verbs" checklist-value="verb.id">
    </td>
    <td>
      {{verb.id}}
    </td>
    <td>
      <span>{{verb.text}}</span>
    </td>
  </tr>

http://plnkr.co/edit/UTtQQJIbtRPdGh0YhRMH?p=preview

这篇关于ng-repeat 不使用 track by 更新模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆