【问题标题】:Prevent change of 'copied' object affecting original using ng-repeat in angular使用 ng-repeat 防止更改“复制”对象影响原始对象
【发布时间】:2015-04-17 16:38:05
【问题描述】:

我有一个角度设置,它显示一个名为“项目”的 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。

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

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

Plunker -

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])); 
 }

【问题讨论】:

  • 尽管 plunker 很不错,但在此处包含您的代码(至少是相关部分)确实会有所帮助。

标签: json angularjs ng-repeat


【解决方案1】:

我推荐使用angular.copy,它是源对象的“深拷贝”。这是来自源对象的唯一对象。

这可能看起来有点违反直觉,但直接引用(如您所见)与原始对象交互。如果您在 DOM 中实例化之后 inspect the element's scope,您可以看到在内存中分配给对象的 $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

【讨论】:

    猜你喜欢
    • 2016-12-01
    • 2020-08-09
    • 2016-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-24
    • 1970-01-01
    • 2015-01-23
    相关资源
    最近更新 更多