替换ng重复内的对象

时间:2016-10-20 11:30:39

标签: angularjs

如何在ng-repeat中替换值。

<div ng-repeat="item in test">
  <input type="text" data-ng-model="item.qty">
</div>

$scope.test = [
        {"InventoryItemID":78689,"Location":"My Location",qty:"2"},
        {"InventoryItemID":78689,"Location":"My Location",qty:"1"}
    ]

现在我必须用test1数量替换测试数量。我怎么能这样做。

$scope.test1 = [
            {qty:"6"},
            {qty:"6"}
        ]

2 个答案:

答案 0 :(得分:2)

您可以使用Object.assign

$scope = this; // Ignore this line

$scope.test = [
        {"InventoryItemID":78689,"Location":"My Location",qty:"2"},
        {"InventoryItemID":78689,"Location":"My Location",qty:"1"}
    ]

$scope.test1 = [
     {qty: "6"},
     {qty: "6"}
]

$scope.test.forEach(function(value, index){
  Object.assign(value, $scope.test1[index])
})

console.log($scope.test)

答案 1 :(得分:2)

您可以拥有一个包含所需值的对象,并使用testtest1作为临时值,例如:

<div ng-repeat="item in items">
  <input type="text" data-ng-model="item.qty">
</div>

var test = [
        {"InventoryItemID":78689,"Location":"My Location",qty:"2"},
        {"InventoryItemID":78689,"Location":"My Location",qty:"1"}
    ]

var test1 = [
            {qty:"6"},
            {qty:"6"}
        ]

$scope.items = test;

然后,交换它,只需:

$scope.items = test1;

这将是“角度方式”。

现场直播:

angular.module('App', [])
.controller('Ctrl', function($scope){
  $scope.test = [
        {"InventoryItemID":78689,"Location":"My Location",qty:"2"},
        {"InventoryItemID":78689,"Location":"My Location",qty:"1"}
    ]

  $scope.test1 = [
            {qty:"6"},
            {qty:"6"}
        ]

  $scope.items = $scope.test;
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="App" ng-controller="Ctrl">
  <div ng-repeat="item in items">
    <input type="text" data-ng-model="item.qty">
  </div>
  <br>
  <button ng-click="items = test">Use Test</button>
  <button ng-click="items = test1">Use Test1</button>
  <br><br>
  {{items}}
</div>

修改

我可能误解了这个问题。

如果您只想更新数量,可以像使用任何其他JavaScript对象一样进行更新,例如,旧式for循环:

for (var i = 0; i < $scope.test.length; i++){
    $scope.test[i].qty = $scope.test1[i].qty;
}