【问题标题】:How do I access dynamically created fields in angularjs?如何访问 angularjs 中动态创建的字段?
【发布时间】:2014-01-29 15:54:30
【问题描述】:

当用户在文本字段中输入的文本通过验证时,我想生成一个新的文本框。现在当新文本框的文本有效时,应该生成另一个文本框。

问题是我做不到,因为创建的名称属于“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);
    }
};

在 If 子句中我希望能够访问 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>

谢谢。

【问题讨论】:

  • 你能提供工作的提琴手吗?

标签: javascript angularjs validation input


【解决方案1】:

尝试通过$index 在您的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>

看看this plunk,你就会明白了。

【讨论】:

  • 我也可以生成文本框。但是我需要在提交表单时检查它们是否有效。
  • 那是什么问题?只需检查 formName.$valid,或将提交按钮的 ng-disabled 绑定到表单的 formName.$invalid 属性,或者为什么不检查 form.contacts 内的项目以查看控制器内是否有空?
  • 查看this fork,查看控制台中的表单错误:。
  • 我可以使用 form.contacts 来查看我的控制器内是否有空的。但是我希望能够将文本验证为电子邮件地址等。如果您查看 HTML,我使用 ng-show 在验证失败时显示错误消息。
猜你喜欢
  • 1970-01-01
  • 2011-03-22
  • 2021-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多