AngularJS:从输入

时间:2016-12-21 08:16:55

标签: angularjs arrays

这是我的方案

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

<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事件以存储值。

但相反,我得到的数组对象包含我在第一个文本框中键入的内容。喜欢这个:

enter image description here

数组取决于创建了多少个表单,所以如果我有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);

}

1 个答案:

答案 0 :(得分:1)

&#13;
&#13;
$scope.forms = [];

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

$scope.forms.push(form1);
&#13;
<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>
&#13;
&#13;
&#13;

同样,

单击add时,您只需要将一个新对象(如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}
]`