I have seen few answers which were working for ng-repeat, but with ng-options I am facing issue.
Problem : Want to show the error message required if the dropdown is touched and nothing is selected, I am able to do this with input fields.
JS CODE
$scope.personMap = [{ name:"Abc", id:"a"},
{ name:"XYZ", id:"b"},
{ name:"FGH", id:"c"},
{ name:"TY", id:"d"}
}]
HTML
<select name="inpName" ng-model="person.name" ng-options="i as i.name for i in personMap track by i.id" required>
<option value="" selected hidden/> </select>
<div ng-messages="form.inpName.$error" ng-if="form.inpName.$touched">
<div ng-message="required">Required field</div>
</div>
</div>
Referred this ng-repeat solution
As there is no answer yet, I am posting the issue i found out.
So when i use
ng-options
it starts adding one extra row in the dropdown which can be blank or you can give something like select me.I added the below code to fix that and in chrome it does not show any blank row.
But when i try in IE it still have a blank row, So what happens is when I select one value in dropdown and then click back on the blank row the
ngMessage
works fine.So if i add one more blank option in chrome and then try to select something first and then click on blank the ngMessage work as expected.Issue is I was expecting
<select> to work like the input fields and was trying to use the
$touched` state. But it does not work like that, I was thinking as soon as i click on the dropdown ngMessage should get active if i leave the focus to other field without selecting anything from dropdown. Not sure if I can make it possible through any other way.Updated HTML