Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs adding dynamically form fields in various forms

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

like image 597
J. Davidson Avatar asked Feb 28 '14 18:02

J. Davidson


1 Answers

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)
like image 119
km6zla Avatar answered Sep 27 '22 22:09

km6zla