Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pushing input values from ng-repeat into array with AngularJS

I have a ng-repeat displaying a list of products with an input each. I want to be able to push the value of each input together with a parameter from every item into a new array to create an order.

So far I managed to do it individually, but not all together.

Here's my HTML:

<div ng-repeat="pa in products">
  <div>
    <h2>{{pa.nom}}</h2>
    <input type="number" ng-model="basket" min="0" max="20" step="1" ng-init="basket=0">
  </div>
</div>
<a ng-click="insert(pa.nom,basket)">Add items</a>

And the function:

$scope.singleorder = [];

$scope.insert = function(nom, basket){
  $scope.singleorder.push({
    'product': nom,
    'number': basket
  });
  console.log($scope.singleorder);
}

I assume the issue has to do with keeping track of the different models of the inputs on each repeat, but I don't know how to deal with it.

I've also tried adding each item individually using ng-change on the input, but it will push an object on every change, duplicating the item on every change, so it won't work.

Any tips?

like image 685
Eric Mitjans Avatar asked Jun 30 '26 03:06

Eric Mitjans


1 Answers

The trick would be to have an input for each repeated element in ng-repeat.

<div ng-repeat="pa in products">
    {{pa.nom}}
    <input type="number" ng-model="pa.basket">
</div>
<a ng-click="insert()">Add items</a>

insert() will loop over products and insert in singleOrder when basket has been set:

$scope.insert = function() {
    for (var i = 0; i < $scope.products.length; i++) {
        if ($scope.products[i].basket) { // if input has been set
            $scope.singleorder.push({
              'product': $scope.products[i].nom,
              'number': $scope.products[i].basket
            });
        }
    }
}

JSFiddle demo

like image 180
Mistalis Avatar answered Jul 01 '26 18:07

Mistalis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!