ng-repeat not update model with track by

笑着哭i 提交于 2019-12-13 02:43:03

问题


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.

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).

Here's a plnkr, Demo

To see the problem, you can follow these steps.

  1. Select any check-box you want
  2. Delete those selected ones
  3. Check the check all button to see,

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


回答1:


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.

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.)

So instead of this:

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

use this:

  <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



来源:https://stackoverflow.com/questions/26472079/ng-repeat-not-update-model-with-track-by

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!