2016-10-20 51 views
1

如何替換ng-repeat中的值。在ng重複中替換對象

<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"} 
     ] 
+0

我不知道如果我理解你的問題,你可以試着重新措辭嗎? – Jordumus

+0

他們有相同的索引嗎? – taguenizy

+0

@Jordumus:我必須用$ scope.test1替換$ scope.test數量值qty – Felixerity

回答

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; 
} 
+0

如果我只需要替換而不是整個對象,該怎麼辦? – Felixerity

+0

只是寫了一個更新。 :) – Shomz

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)