简体   繁体   English

AngularJS:ngMessages在select中无法使用ng-options

[英]AngularJS: ngMessages not working with ng-options in select

I have seen few answers which were working for ng-repeat, but with ng-options I am facing issue. 我几乎没有看到适用于ng-repeat的答案,但是使用ng-options时遇到了问题。

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 JS代码

$scope.personMap = [{ name:"Abc", id:"a"},
{ name:"XYZ", id:"b"},
{ name:"FGH", id:"c"},
{ name:"TY", id:"d"}
}]

HTML 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 推荐此ng-repeat解决方案

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. 因此,当我使用ng-options它会开始在下拉列表中添加额外的一行,该行可以为空白,也可以选择select me。

I added the below code to fix that and in chrome it does not show any blank row. 我添加了以下代码来解决此问题,并且在chrome中,它不显示任何空白行。

<option value=""  selected hidden/> </select>

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. 但是当我尝试在IE中仍然有一个空白行时,那么发生的事情是当我在下拉列表中选择一个值然后单击空白行时ngMessage可以正常工作。所以如果我在chrome中添加另一个空白选项然后尝试首先选择某项,然后按预期单击空白ngMessage工作。

Issue is I was expecting <select> to work like the input fields and was trying to use the $touched` state. 问题是我期望<select> to work like the input fields and was trying to use the $ touched`状态。 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. 但是它不能那样工作,我在想,如果我将焦点移到其他字段而不从下拉列表中选择任何内容,那么我单击下拉列表ngMessage就会立即激活。 Not sure if I can make it possible through any other way. 不知道我是否可以通过其他任何方式使其成为可能。

Updated HTML 更新的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="">Select one </option> </select>
        <div ng-messages="form.inpName.$error" ng-if="form.inpName.$touched">
          <div ng-message="required">Required field</div>
            </div>
           </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM