当输入字段位于 ng-repeat 中时,ng-disabled 不起作用

ng-disabled not working when input fields are in an ng-repeat

如果数组中的输入字段无效,我会尝试禁用我的提交按钮。

这是我的 html

<form name="membersForm">
  <div ng-repeat="emailInput in emailInputs">
    <div class="input-field col s10">
      <input id="email{{$index}}" type="email" class="validate email" length="50" maxlength="50" ng-model="email['email_' + $index]" required>
      <label for="email{{$index}}">{{emailInput.label}}</label>
    </div>
    <div class="input-field col s2">
      <div class="btn btn-floating waves-effect waves-light red" ng-click="removeEmail($index)">
        <i class="material-icons">clear</i>
      </div>
    </div>
  </div>
  <div class="col s12">
    <a class="btn-floating btn waves-effect waves-light" id="addEmail" ng-click="addEmail()">
      <i class="material-icons">add</i>
    </a>
  </div>
  <a class="waves-effect waves-light btn" type="submit" ng-disabled="membersForm.$invalid">
    Continue
  </a>
</form>

如您所见,我有一个按钮可以动态添加更多电子邮件输入。

这是我的控制器:

class teamMembersCtrl {
  constructor($scope) {
    'ngInject';

    $scope.emailInputs = [
      {
        label: 'Email'
      }
    ];

    $scope.email = {};

    $scope.setCurrentPrice();

    $scope.addEmail = function () {
      $scope.emailInputs.push({
        label: 'Email'
      });
    }

    $scope.removeEmail = function ($index) {
      $scope.emailInputs.splice($index,1);
    }
  }
}

问题

如果使用 ng-repeat 动态添加电子邮件输入的电子邮件输入无效,我如何禁用提交按钮?

谢谢!

禁用提交按钮设置 $scope.invalid = true;在你的控制器中,而不是在你的 html ng-disabled="invalid" 中。根据您检查电子邮件输入是否无效的方式,相应地设置 $scope.invalid。

来自 angularjs 文档 forms:

A form is an instance of FormController. The form instance can optionally be published into the scope using the name attribute.

Similarly, an input control that has the ngModel directive holds an instance of NgModelController. Such a control instance can be published as a property of the form instance using the name attribute on the input control. The name attribute specifies the name of the property on the form instance.

This implies that the internal state of both the form and the control is available for binding in the view using the standard binding primitives.

这意味着如果您将 name 属性添加到您的表单,那么您就可以访问该表单及其范围内的所有属性,这意味着您可以访问所有信息你需要验证你的表单,包括它是否有效,原始的还是脏的等等。为了让它工作你需要 2 个主要的东西:

  1. 为您的表单添加名称属性,这将是获取表单数据的变量名称。所以 name = "myform" 将表格存储在 $scope.myform.
  2. ng-model 添加到您的所有输入,如果输入没有 ng-model 则不会在表单验证中考虑它。

之后,您始终可以使用 $scope.myform.$valid 了解您的表格是否有效。作为额外的奖励,您还可以将 name 属性 添加到每个输入,这还将为 $scope.myform 内的每个输入添加一个对象,其中包含该输入的所有信息及其验证。

编辑: 这是一个 plunkr,其中包含您要执行的操作的示例: http://plnkr.co/edit/86p9PrNnFVdfB7y406a6?p=preview