Kim Carlo
Kim Carlo

Reputation: 1223

AngularJS: Creating objects from inputs

Here's my scenario

I am dynamically creating duplicate forms each with same name values.. and another separate form containing other 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 to store these values in an array of objects like this:

[ 
  {"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 inputboxes to store the values.

but instead, I get an array objects that contain what I type on the first textbox. like this one:

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

}

Upvotes: 4

Views: 2135

Answers (1)

Atul Sharma
Atul Sharma

Reputation: 10740

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

Similarly,

on clicking add you only need to push a new object like form1 to $scope.forms and 1 new form will be created on screen.

console.log($scope.forms);

will give you

`[ 
  {"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}
]`

Upvotes: 1

Related Questions