1

我使用角度 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,欢迎任何建议和解决方法

4

2 回答 2

3

您可以在保存消息的元素上使用 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>
于 2016-01-19T13:03:15.307 回答
0

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>
于 2016-02-03T09:37:37.627 回答