gpt4 book ai didi

AngularJS:从输入创建对象

转载 作者:行者123 更新时间:2023-12-02 23:41:15 24 4
gpt4 key购买 nike

这是我的场景

我正在动态创建重复的表单,每个表单具有相同的名称值......以及另一个包含其他信息的单独表单。

<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 函数绑定(bind)到每个输入框的 ng-change 事件来存储值。

但是,我得到了一个数组对象,其中包含我在第一个文本框中键入的内容。就像这个:

enter image description here

数组取决于创建的表单数量,因此如果我有 4 个表单,我的数组中需要有 4 个 json 对象。

下面是我到目前为止的 JavaScript 代码

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

}

最佳答案

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

同样,

单击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}
]`

关于AngularJS:从输入创建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41258085/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com