javascriptangularjsng-messages

AngularJS ng-message directive always showing message


I am trying to set the select field in the view to be required. So I'm having the below tags in my view.html

<form name="homeForm">
  <div class="form-group col-md-6 md-padding">
    <div>
        <label style="font-size: medium">Laboratory Name</label>
        <select name="labName" class="form-control" ng-model="request.labName" required>
            <option ng-repeat="lab in labList" value="{{lab.id}}">{{lab.value}}</option>
        </select>
        <div style="color:maroon" ng-messages="homeForm.labName.$error"
             ng-if="homeForm.requestTypeName.$touched">
            <div ng-message="required">This field is required</div>
        </div>
    </div>

I was hoping the This field is required will show up only when there is no data selected. But irrespective of the field has data or not This field is required shows up like below enter image description here

Is there something I am missing here


Solution

  • The ng-messages directive is in a separate library module and must be included as a dependency.

    Example

    <script src="//unpkg.com/angular/angular.js"></script>
    <script src="//unpkg.com/angular-messages/angular-messages.js"></script>
    

    JS

    angular.module("app",["ngMessages"])
    

    For more information, see AngularJS ngMessages Module API Reference.