AngularJS: creating objects from inputs

Here is my script

I dynamically create duplicate forms with the same name value ... and another separate form containing different information.

<form class="panels" id="form1">
   <input name="invoice_no" class="input-container">
   <input name="description" class="input-container">
   <input name="amount" class="input-container">
</form>

<form class="panels" id="form2">
   <input name="invoice_no" class="input-container">
   <input name="description" class="input-container">
   <input name="amount" class="input-container">
</form>

<form class="panels" id="form3">
   <input name="invoice_no" class="input-container">
   <input name="description" class="input-container">
   <input name="amount" class="input-container">
</form>

<form id="summary">
<input name="totalCost">
<input name="date">
</form>

What I want to do is store these values ​​in an array of such objects:

[ 
  {"invoice_no":123456, "description":"some description","amount":2456},
  {"invoice_no":124578, "description":"abcd deasda ask","amount":1258},
  {"invoice_no":124585, "description":"another description","amount":3698}
]

I want to bind my javascript function to the ng-change event of each input in order to save the values.

but instead, I get array objects that contain what I type in the first text box. like this:

enter image description here

the array depends on how many forms were created, so if I have 4 forms, I need to have 4 json objects inside my array.

below is my javascript code so far

Controller:

$scope.saveData = function(){
    var element = event.target; 
    var object = angular.element(element).closest('.panels').attr('id');
    var value = angular.element(element).closest('.panels').find('.input-container').val();
    var key = angular.element(element).closest('.panels').find('.input-container').attr('name');

    object =  {};
    object [key] = value;       

    arrayOFProducts.push(object);
    console.log(arrayOFProducts);

}
+4
source share
1 answer

$scope.forms = [];

var form1 = {invoice_no : '',description : '', amount : ''  };

$scope.forms.push(form1);
<form class="panels" id="form1" ng-repeat="f in forms">
   <input name="invoice_no" ng-model="f.invoice_no" class="input-container">
   <input name="description" ng-model="f.description" class="input-container">
   <input name="amount" ng-model="f.amount" class="input-container">
</form>
Hide result

,

add , form1, $scope.forms, 1 .

console.log($scope.forms);

`[ 
  {"invoice_no":123456, "description":"some description","amount":2456},
  {"invoice_no":124578, "description":"abcd deasda ask","amount":1258},
  {"invoice_no":124585, "description":"another description","amount":3698}
]`
+1

Source: https://habr.com/ru/post/1664393/


All Articles