[英]ng-change directive in a select is not working properly
I have a select input and a function that is called when the selected value is changed. 我有一个选择输入和一个在更改所选值时调用的函数。 When I change the value using the keyboard arrow keys, the model isn't updated (on the first time). 当我使用键盘箭头键更改值时,模型不会更新(第一次)。 Someone can tell me why? 有人可以告诉我为什么?
JS: JS:
var app = angular.module('myApp',[]);
function mainController($scope) {
$scope.people = [
{
id: 1,
name: 'Julius'
},
{
id: 2,
name: 'Julius Rock'
},
{
id: 3,
name: 'Christopher'
}
];
$scope.selectionChanged = function() {
console.log('test');
};
}
app.controller('mainController', mainController);
HTML: HTML:
<div ng-controller="mainController">
<!-- If you change the value with the arrows ng-change doesn't work on the first change. -->
<select ng-model="selected" ng-options="person.name for person in people track by person.id" ng-change="selectionChanged()"></select>
<span>{{selected}}</span>
</div>
Thanks in advance. 提前致谢。
You want an autofocus on the select element, so that it starts from the first time itself. 您需要在select元素上进行自动对焦,以便从第一次开始。 Added autofocus on select 在select上添加了自动对焦功能
Code Changed: 代码更改:
<select ng-model="selected" ng-options="person.name for person in people track by person.id" ng-change="selectionChanged()" autofocus></select>
This is a known issue, and in fact, is still an open one. 这是一个已知问题,实际上仍然是一个开放的问题。 There are a few ways to get this working how you would expect. 有几种方法可以让您的工作达到预期效果。 You can read about it on the project issue tracker here: select/ngOptions fails to update model after keyboard selection . 您可以在项目问题跟踪器上阅读它: select / ngOptions在键盘选择后无法更新模型 。 As a workaround, you can place an empty <option>
within your <select>
. 作为解决方法,您可以在<select>
放置一个空的<option>
<select>
。 Observe the following change... 观察以下变化......
<select ng-model="selected" ng-options="person.name for person in people track by person.id" ng-change="selectionChanged()">
<option value=""></option>
</select>
JSFiddle Link - updated demo JSFiddle Link - 更新的演示
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.