Angularjs adding dynamically form fields in various forms

All we need is an easy explanation of the problem, so here it is.

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

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

It is not working. Here is the plunker for it:
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=preview
Please let me know where the problem is. Thanks

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

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.

$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 fork of your 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.isUndefined(form.contacts)

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply