gpt4 book ai didi

angularjs ngModel未在选择输入中选择选项

转载 作者:行者123 更新时间:2023-12-01 09:54:36 25 4
gpt4 key购买 nike

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

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

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

最佳答案

除非您为 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>

关于angularjs ngModel未在选择输入中选择选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30872904/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com