Angularjs adds dynamic form fields in various forms

Using ng-repeat, I create a bunch of forms with values ​​in it. Each form has a button for adding lines to this particular form with new fields. Code below

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:

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

He does not work. Here is the plunker for it: http://plnkr.co/edit/THdtLgkwKrV7imqZGjL2?p=preview

Here's what it should look like (the difference is the data object received from db is slightly different from the previously asked question): http://plnkr.co/edit/fETiSYVW7Y5C1yTCwizd?p=preview Please let me know where the problem is. thanks

+7
javascript angularjs angularjs-directive
source share
1 answer

Your addFields method is a problem. Just add the case where form.contacts is undefined and set it to an empty array. Or, run each form element using the contact key set to an empty array.

 $scope.addFields = function (form) { if(typeof form.contacts === 'undefined') { form.contacts = []; } form.contacts.push({name:'', ac: '', a_number: '', p_id: '' }); } 

Works with this change with this plug of your plunger.

Angular also has a helper function to determine when something is undefined, which you might want to use, although I don't know if that really matters.

 angular.isUndefined(form.contacts) 
+3
source share

All Articles