AngularJS 的 ngMessages 模块中 $error 的长度

Length of $error in ngMessages module of AngularJS

这里是使用ngMessages模块的基本方法。 myForm.myName.$error return 错误列表。我想获得错误数量。我试过 {{myForm.myName.$error | json}}.lengthmyForm.myName.$error.length

<form name="myForm">
  <label>
    Enter your name:
    <input type="text"
           name="myName"
           ng-model="name"
           ng-minlength="5"
           ng-maxlength="20"
           required />
  </label>
  <pre>myForm.myName.$error = {{ myForm.myName.$error | json }}</pre>

  <div ng-messages="myForm.myName.$error" style="color:maroon" role="alert">
    <div ng-message="required">You did not enter a field</div>
    <div ng-message="minlength">Your field is too short</div>
    <div ng-message="maxlength">Your field is too long</div>
    <div ng-message-default>This field has an input error</div>
  </div>
</form>

万一你错过了 documentation for the ngMessages module.

By default, ngMessages will only display one message for a particular key/value collection at any time.

这意味着 myForm.myName.$error 最多只能有一个 属性。

如果要支持显示多条消息,请在 ng-messages 指令旁边应用 ng-messages-multiple 属性。应用此功能后,您可以通过创建辅助函数来检索活动错误数。

function getErrorCount() {
    return Object.keys(myForm.myName.$error).length;
}

Here's a demonstration of the suggestion above.