javascript Angularjs 以各种形式动态添加表单字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22103258/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angularjs adding dynamically form fields in various forms
提问by J. Davidson
Using ng-repeat I am creating bunch of forms with values in it. With each form there is also button to add rows to that particular form with new fields. Code is below
使用 ng-repeat 我正在创建一堆带有值的表单。对于每个表单,还有一个按钮可以将行添加到具有新字段的特定表单中。代码如下
HTML:
HTML:
<form name="{{form.name}}"
ng-repeat="form in forms">
<h2>{{form.name}}</h2>
<div ng-repeat="cont in form.contacts">
<input type="text" class="xdTextBox" ng-model="cont.ac"/>
<input type="text" class="xdTextBox" ng-model="cont.a_number"/>
<input type="text" class="xdTextBox" ng-model="cont.p_id"/>
</div>
<button ng-click="submit(form)">Submit</button>
<button ng-click="addFields(form)">Add</button>
<hr>
</form>
Javascript:
Javascript:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.forms = [{
"name" : "form1", "ac": 251, "a_number": "7933", "p_id": 33
}, {
"name": "form2", "ac": 252, "a_number": "7933", "p_id": 4
}, {
"name": "form3", "ac": 253, "a_number": "7362", "p_id": 3
}];
$scope.addFields = function (form) {
form.contacts.push({name:'', ac: '', a_number: '', p_id: '' });
}
$scope.submit = function(form){
console.log(form.contacts);
}
});
It is not working. Here is the plunker for it: http://plnkr.co/edit/THdtLgkwKrV7imqZGjL2?p=preview
它不工作。这是它的 plunker:http://plnkr.co/edit/THdtLgkwKrV7imqZGjL2?p=preview
This is how it should be looking(Difference is data object received from db is little different than this previously asked question): http://plnkr.co/edit/fETiSYVW7Y5C1yTCwizd?p=previewPlease let me know where the problem is. Thanks
这就是它的外观(差异是从数据库接收的数据对象与之前提出的问题略有不同):http: //plnkr.co/edit/fETiSYVW7Y5C1yTCwizd?p=preview请让我知道问题出在哪里。谢谢
采纳答案by km6zla
Your addFields
method is the problem. Just add a case for when form.contacts
is undefined and set it to empty array. Or make each form item start with a contacts key set to an empty array.
你的addFields
方法有问题。只需为何时form.contacts
未定义添加一个案例并将其设置为空数组。或者让每个表单项以设置为空数组的联系人键开始。
$scope.addFields = function (form) {
if(typeof form.contacts === 'undefined') {
form.contacts = [];
}
form.contacts.push({name:'', ac: '', a_number: '', p_id: '' });
}
Works with that change in this forkof your plunk.
在您的 plunk 的这个分支中处理该更改。
Angular also has a helper function for determining when something is undefined you might want to use though I do not know if it really makes any difference.
Angular 还有一个辅助函数,用于确定您可能想要使用的未定义内容,但我不知道它是否真的有什么不同。
angular.isUndefined(form.contacts)