我正在尝试做什么
我正在将一个对象插入数组中,这按预期工作。但是当我尝试通过 $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 中,在 View 中对象是循环的。
// 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));
关于javascript - 通过 $parent.$index 和 $index 更新对象 $scope 项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34944705/