javascript - 通过 $parent.$index 和 $index 更新对象 $scope 项

标签 javascript arrays angularjs object

我正在尝试做什么

我正在将一个对象插入数组中,这按预期工作。但是当我尝试通过 $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/

相关文章:

angularjs - Angular 2 : PrimeNG - XHR error (404 Not Found)

javascript - 未捕获类型错误无法读取未定义的属性 'length'

javascript - 如何在 WEB.API 中显示自定义错误 JSON 结果

c++ - 排序数组c++中的递归二进制搜索

java - 需要帮助处理 json 格式的字符串。 ( java )

javascript - 注册 Angular 1.5 组件时出错

javascript - 格式问题(图像大小、对齐方式等)

javascript - Webpack 构建时不包含对等依赖项

c - For 循环无法正常工作以获取 c 中数组中的输入

javascript - 滑入/滑出目标元素的指令