【问题标题】:angularjs ngModel not selecting option in select inputangularjs ngModel没有在选择输入中选择选项
【发布时间】:2015-09-01 14:03:38
【问题描述】:

ngModel 对于输入类型文本和选择的工作方式是否不同? 选择控件未选择以反映初始模型值。

当我更改 select 的值时,input 和 currentUser.field 也会更改,但如果我将输入文本的值更改为另一个键,则不会发生任何选择。

{{currentUser.field}} // show correct field field key (number) val

// ng-model works => show correct field key (number) val
<input ng-model="currentUser.field" type="text" /> 

// <option value="?" selected="selected" label=""></option> is selected
<select ng-model="currentUser.field" 
   ng-options='item.key as item.value for item in currentUser.collections.field '>
</select>

// only works with input text and {{currentUser.field}}
 <button ng-click='currentUser.field = 305'>select field (int)</button>
 <button ng-click='currentUser.field = "305"'>select field (string)</button>

【问题讨论】:

  • item.key 是数字还是字符串? currentUser.field 是数字还是字符串?
  • 我尝试了任何一种方式,初始 item.key 是 (int) currentUser.field 是 (int)

标签: angularjs angularjs-ng-model angularjs-ng-options


【解决方案1】:

除非您将值设置为currentUser.field,否则您的代码应该可以正常工作:

var app = angular.module('app', []);

app.controller('myController', function($scope) {
  $scope.currentUser = {
    collections: {
      field: [{
        key: '1',
        value: 'one'
      }, {
        key: '2',
        value: 'two'
      }, {
        key: '3',
        value: 'three'
      }]
    }
  };
  $scope.currentUser.field = "2";
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<div ng-app='app' ng-controller='myController'>
  <h3>expression</h3>
  {{currentUser.field}}
  
  <h3>input</h3>
  <input ng-model='currentUser.field' type='text'>
  
  <h3>select</h3>
  <select ng-model='currentUser.field' ng-options='item.key as item.value for item in currentUser.collections.field'></select>
  
  <h3>buttons</h3>
  <button ng-click='currentUser.field="305"'>305</button>
  <button ng-click='currentUser.field="1"'>1</button>
</div>

【讨论】:

  • 是的 305 不在选项中,而且事实证明类型很重要如果 item.key 是 (int) 就我而言,“305”将不起作用
猜你喜欢
  • 2014-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-09
  • 1970-01-01
  • 2018-08-21
  • 2015-03-04
  • 2017-07-13
相关资源
最近更新 更多