2014-01-29 88 views
0

當用戶在文本字段中輸入的文本通過驗證時,我想生成一個新的文本框。現在,當新文本框的文本有效時,應該生成另一個文本框。如何訪問angularjs中動態創建的字段?

問題是我無法做到這一點,因爲創建的名稱是'email1''email2''email3'類型。而且我無法訪問這些動態生成的字段。

JS代碼片段:

var master = { 
    name: 'John Smith', 
    address: { 
     line1: '123 Main St.', 
     city: 'Anytown', 
     state: 'AA', 
     zip: '12345' 
    }, 
    contacts: [{ 
     type: 'phone', 
     value: 'This is a value', 
     validationtype: 'number' 
    }] 
}; 

$scope.addContact = function(contact) { 
    var valueOfContact = $scope.form.contacts.value; 
    console.log(valueOfContact); 
    if ($scope.myForm.email.$valid == true) { 
     tbCounter++; 
     $scope.form.contacts.push({ 
      type: 'email', 
      value: '', 
      name: 'email' + tbCounter, 
      id: 'email' + tbCounter 
     }); 
     console.log($scope.form.contacts.indexOf(contact), $scope.form.contacts.length); 
    } 
}; 

在我希望能夠訪問EMAIL1,EMAIL2等等。如果條款。

HTML摘錄:

<div ng-repeat="contact in form.contacts"> 
    <label>{{ contact.type }}</label> 
    <input name ="{{ contact.name }}" type="{{ contact.type }}" ng-model="contact.value" ng-change=addContact(contact) required/> 
    <span class="error" ng-show="myForm.email.$error.required">required</span> 
    <span class="error" ng-show="myForm.email.$error.email">invalid email</span> 
</div> 

感謝。

+0

你能提供工作小提琴嗎? –

回答

3

嘗試通過$indexng-repeat內訪問每一元素:

<div ng-repeat="contact in form.contacts"> 

     <label>{{ form.contacts[$index].type }}</label> 
     <input name="form.contacts[$index].name" type="form.contacts[$index].type" ng-model="form.contacts[$index].value" ng-change="addContact(contact)" required /> 

</div> 

this普拉克看一看,你就會明白我的意思。

+0

我也能夠生成文本框。但是當我提交表格時,我需要檢查他們每個人是否有效。 –

+0

所以最新的問題?只需檢查formName。$ valid,或將提交按鈕的ng-disabled綁定到窗體的formName。$ invalid屬性,或者爲什麼不檢查'form.contacts'中的項目以查看控制器內是否有空的項目? –

+0

查看[this fork](http://plnkr.co/edit/JZoLnrlTD6SBzh4nyGf7?p=preview),注意表單錯誤的控制檯: –