添加重复键对象时如何更新 ng-repeat 列表中的元素

How to update element in ng-repeat list when duplicated key object gets added

本文关键字:ng-repeat 更新 列表 元素 对象 何更新 添加      更新时间:2023-09-26
<table>
    //thead[...]
    <tr ng-repeat="user in users track by user.username">
        <td>{{user.username}}</td>
        ...
    </tr>
</table>

每当我添加一个元素($scope.users.push(newUser);),其键在ng-repeat列表中重复时,我都会收到错误:

Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: user in users, Duplicate key: username

我对此没意见,但我希望使用新对象的值更新旧对象。换句话说,我希望它更新或替换。

我在谷歌上找不到任何帮助,所以我迷路了。

使用 .

splice 而不是 .push 来添加/删除(基本上替换)数组中的项目。

很烦人,因为它可能是这样的(更像是伪代码,因为我真的不知道你的大部分代码):

for (var i =0; i <=length_of_array; i++){
   if  (array[i].admin == new_element.admin)
   {
       array[i] = new_element;
      new_element =null;
   }
}
if (new_element != null)
{
   array.push(new_element)
}
就像我说的,

没有任何更多的上下文,这基本上是我推荐的,我不是角度专家,但除非有一个我不知道的特定角度解决方案,否则这是同时的替代选择。