How do I access dynamically created fields in angu

2019-09-03 03:14发布

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'. And I'm not able to access these dynamically generated fields.

JS Snippet:

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.

HTML Snippet:

<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.

1条回答
Emotional °昔
2楼-- · 2019-09-03 03:46

Try accessing each of those elements by $index inside your ng-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>

Have a look at this plunk, you'll get the idea.

查看更多
登录 后发表回答