设置 $invalid 和 $error 不会使表单无效

Setting $invalid and $error doesn't invalidate the form

我有一个表格,我正在将我的 phone 字段从使用正则表达式更改为 intl-tel-input 模块。我 运行 在检查有效 #s 时遇到问题和困惑。

我有一个包含其中几个字段的表单...

<div class="row">
<div class="col-xs-2">
    <label for="cellPhone"
           translate>CONTACT.CELL</label>
</div>
<div class="col-xs-6"
     ng-class="{'has-error': !cellPhoneFocus && forms.contactForm.cellPhone.$invalid && forms.contactForm.cellPhone.$touched }">
    <input type="text" class="form-control intlPhoneInput"
           id="cellPhone" name="cellPhone"
           ng-model="contact.cellPhone.display"
           ng-focus="cellPhoneFocus = true"
           ng-blur="cellPhoneFocus = false; validatePhone($event)">
    <div ng-messages="forms.contactForm.cellPhone.$error"
         ng-show="!cellPhoneFocus && forms.contactForm.cellPhone.$touched"
         class="errorMessages">
        <p ng-message="pattern" translate>
            CRUD.VALID_PHONE</p>
    </div>
</div>

然后提交...

<button type="submit" class="btn btn-primary" ng-disabled="forms.contactForm.$invalid" id="saveContactLink" translate>CRUD.SAVE</button>

然后在我的控制器 (Typescript) 中...

//In Constructor
$scope.validatePhone = this.validatePhone.bind(this);

//Outside constructor
private validatePhone(eventObject: any) {
    let thePhoneField = $('#' + eventObject.target.id);
    let phoneIsValid = thePhoneField.intlTelInput("isValidNumber");

    this.$scope.forms.contactForm[eventObject.target.id].$invalid = !phoneIsValid;
    this.$scope.forms.contactForm[eventObject.target.id].$error = {"pattern": !phoneIsValid};
}

这正确地设置了我的 has-error class 和错误消息,但它没有将 FORM 设置为无效。我试过 $setValidity...

this.$scope.forms.contactForm[eventObject.target.id].$setValidity('pattern', !phoneIsValid);

...但它似乎根本没有做任何事情。

如何将字段设置为无效,显示正确的 ng-message(如果有多个),并确保更新 $errors 表单以便禁用提交?

您应该可以像这样将表单设置为无效:

forms.contactForm.$invalid = true

原来 $setValidity 是工作的,但是 setValidity 与 .$invalid 和 $error 一起导致了一些交叉线。在使字段无效时正确注释掉最后两个 enabled/disabled 我的提交按钮。