这是我的情景
我正在动态创建每个具有相同名称值的重复表单..以及包含其他信息的另一个单独表单.
<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>
我想要做的是将这些值存储在一个对象数组中,如下所示:
[
{"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}
]
我想将我的javascript函数绑定到每个输入框的ng-change事件以存储值.
但相反,我得到一个数组对象,其中包含我在第一个文本框中键入的内容.像这个:
数组取决于创建了多少个表单,所以如果我有4个表单,我需要在我的数组中有4个json对象.
下面是我到目前为止的JavaScript代码
控制器:
$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);
}
最佳答案
$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>
同样的,
在单击添加时,您只需要将一个新对象(如form1)推送到$scope.forms,并在屏幕上创建一个新表单.
的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}
]`