Felixerity Felixerity - 1 month ago 9
AngularJS Question

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

Answer

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