2014-02-28 41 views
7

使用ng-repeat我創建了一堆帶有值的表單。每個表單都有一個按鈕,可以將新行添加到特定表單中。代碼如下Angularjs以各種形式動態添加表單字段

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

這是怎麼回事應該看(區別是從數據庫接收到的數據對象比這之前問的問題略有不同): http://plnkr.co/edit/fETiSYVW7Y5C1yTCwizd?p=preview 請讓我知道問題出在哪裏。謝謝

回答

3

您的addFields方法是問題所在。只需添加一個案例,當form.contacts未定義,並將其設置爲空陣列。或者使每個表單項都以聯繫人鍵設置爲空數組開始。

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

適用於您的plunk的this fork變化。

Angular還有一個幫助函數,用於確定何時未定義的東西,您可能想要使用,但我不知道它是否真的有任何區別。

angular.isUndefined(form.contacts) 
相關問題