更改 Angular 中 select 元素的模型会添加一个值为 value="?" 的选项

Changing the model of a select element in Angular adds an option with value="?"

我的 angular 应用程序中有一个 select 元素绑定到一个模型。当我更改模型 angular 时,出于某种原因,添加了一个额外的选项,值为 value="?"。 Here is a jsFiddle 来说明我的观点。为什么会发生这种情况,如何避免?

angular.module('angularApp', []);

function testCtrl($scope, $timeout)
{
    $scope.options = [1,2,3];
    $scope.initialSelectedValue = 2;
    
    
    $timeout(function(){
    
    $scope.options = [4,5,6];
    
    }, 3000)
    
}
<div ng-app="angularApp">
    <div ng-controller="testCtrl">
        <select ng-model="initialSelectedValue" ng-options="option for option in options"></select>
    </div>
</div>

编辑: 我知道我可以简单地添加一个带有 value="" 的选项作为快速修复,但在我的情况下我不能没有这个选项。

发生这种情况是因为您正在中间更改列表,而 ViewModel initialSelectedValue(命名不当,因为它不仅是初始值,而且是实际的当前选定值)悬而未决,而不是指向 select.

的任何有效选项

这样做是为了使模型不会改变 "under the covers",并且只能 set/changed 显式地通过控制器或输入的变化来实现。

要解决此问题,只需在更改列表时将模型更改为可用选项之一即可:

$scope.options = [1,2,3];
$scope.selectedValue = 2; // I changed the name

$timeout(function(){

    $scope.options = [4,5,6];
    $scope.selectedValue = $scope.options[0];

}, 3000)