Angularjs以各种形式动态添加表单字段

时间:2014-02-28 18:40:33

标签: javascript angularjs angularjs-directive

使用ng-repeat我正在创建一堆带有值的表单。对于每个表单,还有一个按钮,用新字段向该特定表单添加行。代码如下

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

它不起作用。这是它的plunker: http://plnkr.co/edit/THdtLgkwKrV7imqZGjL2?p=preview

它应该是这样看的(差异是从db接收的数据对象与之前提出的问题有点不同): http://plnkr.co/edit/fETiSYVW7Y5C1yTCwizd?p=preview 请告诉我问题所在。谢谢

1 个答案:

答案 0 :(得分:3)

您的addFields方法就是问题所在。只需为form.contacts未定义时添加一个案例,并将其设置为空数组。或者使每个表单项以联系人键设置为空数组开始。

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

在你的插件的this fork中使用该更改。

Angular还有一个帮助函数,用于确定何时未定义您可能想要使用的内容,但我不知道它是否真的有任何区别。

angular.isUndefined(form.contacts)