javascript - ng-model 从下拉列表中获取错误的值

标签 javascript angularjs drop-down-menu angular-ngmodel

当某些值在标题处共享起始字母时,在下拉列表中输入时,我的 ng-model 会更新为第一个值。

 <div ng-app="dropDown" ng-controller="dropDownController">
      <select name="StateId" ng-model="selectedState" class="form-control" ng-change="selectedStateChanged()" ng-options="(states.Abbrev + ' - ' + states.Name) for states in states"></select>
      <span>{{selectedState.Name||''}}</span>
    </div>

Plnkr http://plnkr.co/edit/pLVzK18iJxrmrL9Oiw4b?p=preview

测试场景:

  1. 单击表单的任意部分。
  2. 单击 Tab 键以将焦点置于下拉列表中。
  3. 开始输入“TX”

结果: - “TX - TEXAS”选项显示在下拉列表中。 - $scope.selectedState 值是 {Name:'TENNESSEE'}

预期:

  • “TX - TEXAS”选项显示在下拉列表中。
  • $scope.selectedState 值应为 {Name:'TEXAS'}

我将使用纯 JavaScript 来解决这个问题,同时,我想知道是否有任何 AngularJS 解决方案。

提前致谢。

最佳答案

我在 select 方面也遇到了一些问题。这就是为什么添加空的 option-tag 总是更安全!

<div ng-app="dropDown" ng-controller="dropDownController">
  <select name="StateId" ng-model="selectedState" class="form-control" ng-change="selectedStateChanged()" ng-options="(states.Abbrev + ' - ' + states.Name) for states in states">
    <option></option>
  </select>
  <span>{{selectedState.Name||''}}</span>
</div>

解决方案:http://plnkr.co/edit/LfS347JM6V7Rv5S6vPkL?p=preview


Angular Documentation解释一下问题:

If the viewValue of ngModel does not match any of the options, then the control will automatically add an "unknown" option, which it then removes when the mismatch is resolved.

Optionally, a single hard-coded element, with the value set to an empty string, can be nested into the element. This element will then represent the null or "not selected" option.

关于javascript - ng-model 从下拉列表中获取错误的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32999394/

相关文章:

css - MaterializeCSS 中的选择未填充来自 VUE 的数据

javascript - Angularjs 单选按钮没有给出 json 中的默认值

Javascript:将函数指针放入对象中?

javascript - 关闭弹出窗口时暂停当前视频

javascript - AngularJS 1.3 使用一次性绑定(bind)手动更新绑定(bind)

php - 如何在 GridView::widget、Yii2 的搜索框中使用简单的下拉列表?

asp.net-mvc - ViewBag 幕后花絮

javascript - 无法使用 bower 下载 three.js 文件

javascript - AngularJS 范围仅有时刷新

javascript - AngularJS:指令重复,作为属性而不是元素