gpt4 book ai didi

json - 使用 ng-repeat in angular 防止影响原始的 'copied' 对象的更改

转载 作者:行者123 更新时间:2023-12-05 01:00:14 24 4
gpt4 key购买 nike

我有一个 angular 设置,它显示一个名为“items”的 json 字符串。每个项目都包含一个字段 ID 数组。通过匹配字段 ID,它使用单独的“字段”json 字符串提取字段的信息。

 {
"data": [
{
"id": "1",
"title": "Item 1",
"fields": [
1,
1
]
},
{
"id": "2",
"title": "Item 2",
"fields": [
1,
3
]
},
{
"id": 3,
"title": "fsdfs"
}
]
}

您可以复制或删除项目或字段,这将修改“项目”json。

一切正常,除非我复制一个项目(及其字段),然后选择删除该特定项目的一个字段。

发生的情况是它删除了复制项目和原始项目的字段。

普朗克 -

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

我读过使用“track by”有助于将每个项目索引为唯一的并防止重复键,但这似乎没有效果。

任何帮助表示赞赏,谢谢

编辑 -

归功于 Eric McCormick,使用 angular.copy 和 array.push 解决了这个问题。

代替 -
$scope.copyItem = function (index) {
items.data.push({
id: $scope.items.data.length + 1,
title: items.data[index].title,
fields: items.data[index].fields
});
}

这有效 -
$scope.copyItem = function (index) {
items.data.push(angular.copy(items.data[index]));
}

最佳答案

我建议使用 angular.copy ,它是源对象的“深拷贝”。这是来自源头的独特对象。

这似乎有点违反直觉,但直接引用(如您所见)与原始对象交互。如果您 inspect the element's scope在 DOM 中实例化之后,您可以看到有一个 $id 属性分配给内存中的对象。基本上,通过使用 angular.copy(source, destination),您可以确保复制所有属性/值并拥有一个唯一的对象。

例子:

//inside the controller, a function to instantiate new copy of selected object
this.selectItem = function(item){
var copyOfItem = angular.copy(item);
//new item with same properties and values but unique object!
}

Egghead.io 有 a video on angular.copy .

关于json - 使用 ng-repeat in angular 防止影响原始的 'copied' 对象的更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29704886/

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