angularjscountng-messages

Length of $error in ngMessages module of AngularJS


Here is the basic way to use ngMessages module. myForm.myName.$error return list of error. I want to get number of errors. I have tried {{myForm.myName.$error | json}}.length and myForm.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>

Solution

  • In case you missed it in the documentation for the ngMessages module.

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

    This means myForm.myName.$error can only ever have a maximum of one property.

    If you want to support the display of multiple messages, apply the ng-messages-multiple attribute alongside the ng-messages directive. With this applied, you can retrieve the number of active errors by creating a helper function.

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

    Here's a demonstration of the suggestion above.