4

I'm new to angularjs and I was just wondering about what ngMessage 'ng-messages' attribute can do.

I'm trying to display one ngMessage for multiple input[type=text] elements. for example:

<input type="text" id="name1" ng-model="person.name1" />
<input type="text" id="name2" ng-model="person.name2" />
<input type="text" id="name3" ng-model="person.name3" />
<input type="text" id="name4" ng-model="person.name4" />

<div id="error" 
ng-messages="person.name1.$error || 
             person.name2.$error || 
             person.name3.$error || 
             person.name4.$error"

ng-show="person.name1.$touched || 
         person.name2.$touched || 
         person.name3.$touched || 
         person.name4.$touched"
ng-include="errorMsg.html"
/>

One validation message will display for all 4 input[type=text] attribute.

dei
  • 41
  • 5

2 Answers2

1

Try To use it it in the below manner:-

<form name="Form_Name">
  <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>
</form>
Shian JA
  • 848
  • 4
  • 15
  • 52
  • 1
    I'm thinking of multiple input[type=text] to display a single ng-messages directive. sorry but this didn't solve the question. thanks for the answer though.. :) – dei Jun 08 '15 at 09:24
  • 2
    By default, ngMessages will only display one error at a time. However, if you wish to display all messages then the ng-messages-multiple attribute flag can be used on the element containing the ngMessages directive to make this happen. – Shian JA Jun 08 '15 at 09:27
  • 2
    I want to display one error from multiple input[type=text] and not display multiple error from a single input[type=text]. – dei Jun 08 '15 at 09:35
  • 2
    You can use ng-messages=”.$error” For Full Form Validation – Shian JA Jun 08 '15 at 09:40
  • 1
    I tried that Full Form Validation and it worked but my requirement is to show specific validation message for multiple input[type=text] so I was hoping to know if ng-messages accept multiple $error objects like this one. ng-messages="{$scope.object}.{fieldname}.$error, {$scope.object}.{fieldname}.$error, {$scope.object}.{fieldname}.$error" – dei Jun 08 '15 at 09:53
  • I don't think it's possible – Shian JA Jun 08 '15 at 10:00
1

The best solution I have come across so far is to group the fields you want with data-ng-form='subform' name='subform' and then for the messages element: data-ng-messages='subform.$error'

Kraken
  • 5,043
  • 3
  • 25
  • 46