Angular JS 'ng-if' is not working as expected

Clash Royale CLAN TAG#URR8PPP
Angular JS 'ng-if' is not working as expected
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
This field is required
This field is required
Is there something I am missing here
2 Answers
2
You are using homeForm.requestTypeName in the ng-if, and there is no input control named requestTypeName, i guess you must use "homeForm.labName" as you use in the ng-message attribute.
Basically, change the ng-if to ng-if="homeForm.labName.$touched"
TL;DR;
You could use as well the homeForm.labName.$error.required for cheking if actually the end user has passed away that field without entering some input. Source: https://docs.angularjs.org/api/ng/directive/ngRequired
homeForm.labName.$touched
You need to set the same input name in your input and in your ng-message. Doing this, you don't even need to have ng-if. For example:
<input name="fullname" type="text" ng-model="fullname" required/>
<div ng-messages="form.$submitted && form.fullname.$error">
<p ng-message="required" class="help-block">This field is required</p>
</div>
In this case I am using form.$submitted. You can remove that, replace it with touched/dirty or whatever. The principle is the same.
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Sorry that was a typo I have
homeForm.labName.$touchedstill behaves the same– trx
2 mins ago