AngularJS:ngMessages在select中不能与ng-options一起使用 [英] AngularJS: ngMessages not working with ng-options in select

查看:92
本文介绍了AngularJS:ngMessages在select中不能与ng-options一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我几乎没有找到适用于ng-repeat的答案,但是使用ng-options时我遇到了问题.

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

$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>

已引用此 ng-repeat解决方案

推荐答案

由于尚无答案,我将发布发现的问题.

As there is no answer yet, I am posting the issue i found out.

因此,当我使用ng-options时,它将开始在下拉列表中添加额外的一行,该行可以为空白,也可以选择选择我".

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.

我添加了以下代码来修复此问题,并且在chrome中,它不会显示任何空白行.

I added the below code to fix that and in chrome it does not show any blank row.

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

但是当我在IE中尝试它时仍然有一个空白行,所以发生的事情是当我在下拉列表中选择一个值然后单击空白行时ngMessage正常工作.因此,如果我再添加一个空白选项在chrome中,然后尝试首先选择某些内容,然后按预期方式在空白ngMessage上单击空白.

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.

问题是 我期待的是<select> to work like the input fields and was trying to use the $ touched`状态.但是它不能那样工作,我在想,如果我将焦点移到其他字段而不从下拉列表中选择任何内容,那么我单击下拉列表ngMessage就会立即激活.不知道我是否可以通过其他任何方式使之成为可能.

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.

更新的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>

这篇关于AngularJS:ngMessages在select中不能与ng-options一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆