Reshav
Reshav

Reputation: 545

replace object inside ng repeat

how can i replace value inside 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"}
    ]

now i have to replace the test qty with test1 qty . how can i do that.

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

Upvotes: 1

Views: 836

Answers (2)

Shomz
Shomz

Reputation: 37701

You can have one object that hold the values you need, and use test and test1 as temporary values, for example:

<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;

Then, to swap it, just do:

$scope.items = test1;

That would be the "Angular way" of doing it.


See it live:

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>


EDIT

I might've misread the question.

If you just want to update quantities, you can do it just like with any other JavaScript object, for example, an old-school for-loop:

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

Upvotes: 2

taguenizy
taguenizy

Reputation: 2265

You could use 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)

Upvotes: 2

Related Questions