按 $parent.$index 和$index更新对象$scope项

Update Object $scope item by $parent.$index and $index

本文关键字:index scope 对象 parent 更新      更新时间:2023-09-26

我试图做什么

我将一个对象推入数组,这按预期工作。但是当我尝试通过它们的 $parent.$index 更新数组中的一个对象并$index所有对象都已更新时。

对象被推入数组(多次)

// Array for Objects
$scope.arr = []
// Object to be pushed into Array
$scope.obj = {
   content:[
      {
         type:"text",
         data:"This is Dummy Text",
         style:{
           "height":"500px"
         }
      },
      // Could be more than one Object within Content
   ]
}

上述对象将被多次推送到 $scope.arr 中,在视图中对象被循环。

// Looped Arrays
<div ng-repeat="l1 in arr track by $index">
  <div ng-repeat="l2 in l1.content" ng-style="l1.style">{{l1.data}}</div>
</div>

按 $parent.$index 和$index更新

因此,在这一点上,我已经多次将 $scope.obj 推送到 $scope.arr 中,这就是问题发生的地方。

我只需要通过如下代码行更新 $scope.arr 中的一个 $scope.obj:

// Set $index's to target the specific array items
var parentIndex = 0
var index = 0
$scope.arr[parentIndex].content[index].style['height']

可能的更新示例如下:

var o = parseInt($scope.arr[parentIndex].content[index].style['height'])
var n = o + 1
$scope.arr[parentIndex].content[index].style['height'] = new + 'px'

目前,尽管设置了正确的 $parent.$index 和$index,但上述内容将更新 $scope.arr 中的所有插入/推送对象。我需要定位和更新一个,而不是全部。

我一定在这里错过了一些东西,任何帮助或指导都非常感谢。

推送时,尝试像这样复制对象:

$scope.arr.push(angular.copy($scope.obj));

由于您将代码的重要部分保密(如何将"对象"插入"数组"),我只能猜测,您正在将同一对象"插入"到多个位置(意味着:您将对同一对象的引用保留在数组的多个索引中,因此基本上您只有 1 个对象),然后当您使用 array[1].object.a=2 在"1 位"更改对象时, 然后你会看到"each"索引的变化:array[4].object.a==2,因为它们实际上引用了同一个对象。