AngularJS - 如何在更改字段后设置有效性为真

AngularJS - How to set validity true after change the field

我已经按照 到 运行 自定义服务器端唯一电子邮件约束验证。

这是我在控制器上的提交功能:

function submit(form){
  CompanyUser.save(vm.model)
      .success(function(data) {
          vm.closeModal();
          toastSucess(data);
      })
      .error(function(data) {
          if(data.code == 'error_duplicated_email')
              form['email'].$setValidity("uniqueEmail", false);
      });

}

这里是我的电子邮件 HTML 代码:

<form name="form" novalidate ng-click="form.$valid && vm.submit(form)">
    <div class="form-group" ng-class="{ 'has-error': form.$submitted && form.email.$error.uniqueEmail }">
        <label>E-mail</label>
        <input type="email" class="form-control" name="email" ng-model="vm.model.email" required>
        <span ng-show="form.$submitted && form.email.$error.uniqueEmail" class="help-block">Duplicated e-mail</span>
    </div>
    <div class="modal-footer">
        <button type="button" class="btn btn-white" ng-click="vm.closeModal()">Cancel</button>
        <button type="submit" class="btn btn-primary">Save</button>
    </div>
</form>

并且在服务器 returns 出错后工作正常。但是,然后我更改了电子邮件并尝试提交,但我不能再这样做了。我认为那是因为我已将 validity 设置为 false。那么如何设置为true来尝试再次提交表单呢?

您可以尝试使用$setPristine();方法。

来自 angular documentation:

$setPristine(); Sets the form to its pristine state.

This method sets the form's $pristine state to true, the $dirty state to false, removes the ng-dirty class and adds the ng-pristine class. Additionally, it sets the $submitted state to false.

This method will also propagate to all the controls contained in this form.

Setting a form back to a pristine state is often useful when we want to 'reuse' a form after saving or resetting it.

这是来自@code90 的解决方案:

我需要在 <input type="email"..

中添加一个 ng-change="form.$valid=true"

而且效果很好!