[英]How do I access dynamically created fields in angularjs?
When the text entered by the user in a text field passes the validation, I want to generate a new textbox. 当用户在文本字段中输入的文本通过验证时,我想生成一个新的文本框。 Now when the text of the new textbox is valid, another textbox should be generated.
现在,当新文本框的文本有效时,应生成另一个文本框。
The problem is I am not able to do it, because the names of the that get created are of the type 'email1' 'email2' 'email3'. 问题是我无法执行此操作,因为创建的的名称类型为'email1''email2''email3'。 And I'm not able to access these dynamically generated fields.
而且我无法访问这些动态生成的字段。
JS Snippet: 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);
}
};
In the If clause I want to be able to access email1, email2 and so on. 在If子句中,我希望能够访问email1,email2等。
HTML Snippet: 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>
Thanks. 谢谢。
Try accessing each of those elements by $index
inside your ng-repeat
: 尝试通过
ng-repeat
$index
访问每个元素:
<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>
Have a look at this plunk, you'll get the idea. 看看这个小问题 ,您会明白的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.