Eric Mitjans
Eric Mitjans

Reputation: 2179

Pushing values from multiple inputs from ng-repeat into array with AngularJS

I have the following array:

$scope.variations = [
    {'nom':'',
     'preu':0,
     'grams':''
    },
    {'nom':'',
     'preu':0,
     'grams':''
    },
    {'nom':'',
     'preu':0,
     'grams':''
    }
];

And I display it in the frontend like so:

<div ng-repeat="vari in variations">
  <input type="text" class="inputmodal" ng-model="varinom">
  <input type="text" class="inputmodal" ng-model="varipreu">
  <input type="text" class="inputmodal" ng-model="varigrams">
</div> 

Once I fill the 3 inputs in all 3 items of the array, I'm trying to push each one of them into another array, like so:

<a ng-click="test()">TEST</a>

And the JS:

 $scope.test = function(){
   $scope.singleorder = [];
   for(var i = 0; i < $scope.variations.length; i++)
     $scope.singleorder.push({
       'nom': $scope.variations[i].varinom,
       'grams': $scope.variations[i].varigrams,
       'preu': $scope.variations[i].varipreu,
     });

  console.log($scope.singleorder);
};     

On my results in the console, I have 3 arrays in the console, but the values of each object are undefined.

What am I missing?

Upvotes: 0

Views: 638

Answers (1)

Satpal
Satpal

Reputation: 133423

You have set ngModel correctly. use reference variable vari like

<div ng-repeat="vari in variations">
  <input type="text" class="inputmodal" ng-model="vari.nom">
  <input type="text" class="inputmodal" ng-model="vari.preu">
  <input type="text" class="inputmodal" ng-model="vari.grams">
</div> 

and use

 $scope.singleorder.push({
   'nom': $scope.variations[i].nom,
   'grams': $scope.variations[i].grams,
   'preu': $scope.variations[i].preu,
 });

Upvotes: 1

Related Questions