根据多个条件显示带有 ng-messages 的验证消息

Display validation message with ng-messages based on multiple conditions

我使用 angular ng-messages 来显示验证消息

考虑以下代码:

<ul ng-messages="formToValidate.fieldToValidate.$error" ng-messages-multiple>
    <li ng-message="pattern">Invalid pattern</li>
    <li ng-message="minlength, maxlength">Should contain no less than 7 and no more than 100 chars</li>
    <li ng-message="!pattern && !minlength && !maxlength && onlyAfterAllOtherPassedValidation">
        This validation message is shown only when all the other validations have passed and validation  fails on onlyAfterAllOtherPassedValidation
    </li>
</ul>

我只想在所有其他验证都已通过且 onlyAfterAllOtherPassedValidation 验证失败时显示最后一条验证消息。 而且我不知道是否有可能将复杂的条件传递给 ng-message 只要我仍然可以使用 ng-messages

,欢迎任何建议和解决方法

您可以在包含消息的元素上使用 ng-if,例如

<li ng-if="!formToValidate.fieldToValidate.$error.required && !formToValidate.fieldToValidate.$error.minLength && !formToValidate.fieldToValidate.$error.maxLength" ng-message="onlyAfterAllOtherPassedValidation">
    This validation message is shown only when all the other validations have passed and validation  fails on onlyAfterAllOtherPassedValidation
</li>

JonMac1374 提出的解决方案当然有效。但是最好一劳永逸地解决这个问题。我建议你注意指令 use-form-error。它有助于建立自己的支票。

jsfiddle.

上的实例
<form name="ExampleForm">
  <label>Password</label>
  <input ng-model="password" name="password" minlength="2" pattern="^\d*$" required use-form-error="onlyAfterAllOtherPassedValidation" use-error-expression="!ExampleForm.password.$error.required && !ExampleForm.password.$error.minlength && !ExampleForm.password.$error.pattern"
  />
  <pre>{{ExampleForm.password.$error|json}}</pre>
  <div ng-messages="ExampleForm.password.$error" ng-messages-multiple="true" class="errors">
    <div ng-message="required">
      Your required is wrong
    </div>
    <div ng-message="pattern">
      Your pattern is wrong
    </div>
    <div ng-message="minlength">
      Your minlength is wrong
    </div>
    <div ng-message="onlyAfterAllOtherPassedValidation">
      Your onlyAfterAllOtherPassedValidation
    </div>
  </div>
</form>