Angular select 不显示下拉列表默认值

Angular select not displaying dropdown default

下面有这个html

<select name="reason" class="form-control" ng-model="reasonSelected" 
ng-options="reason for reason in reasonList" required></select>

在我的 angular 控制器的开头我有

$scope.reasonSelected = $scope.item.stsChangeReason;
$log.debug("$scope.reasonSelected = " + $scope.reasonSelected);

正在将下面的内容打印到控制台,但仍然没有默认值

LOG: $scope.reasonSelected = someValue

在其他一些初始化函数中我有

$scope.reasonList = response;

如果我这样做

$scope.reasonSelected = $scope.reasonList[0];

然后我看到一个默认值。我在这里遗漏了一些明显的东西吗?

我必须查看您用于 ng-options 的数据,但听起来您没有将其正确初始化为您想要的值。根据您的数据,您可能需要执行 ng-options="reason.id as reason.name for reason in reasonList" 之类的操作,但从它的声音来看,执行 $scope.reasonSelected = $scope.reasonList[0]; 听起来很正常。查看同一问题的其他答案:

这是 AngularJS 中的常见错误。为了设置为默认值,您需要确保 reasonSelected 范围变量持有对所需 reasonList 范围数组变量项的引用(如您在调查中所见)。

根据您使用的是字符串数组、对象数组还是其他内容,您问题的答案会略有不同。

编辑:问题是您的 ng-options 参数不正确。使用 select as label for value in array 综合表达式。注意 as.

<select name="reason" class="form-control" ng-model="reasonSelected" 
    ng-options="reason as reason for reason in reasonList" required></select>

假设一个字符串数组:http://plnkr.co/edit/06c5pQ?p=preview

我这样做了并且成功了

$scope.reasonSelectedSaved = $scope.item.stsChangeReason;

在初始化函数中

$scope.reasonList = response;
$scope.reasonSelected = $scope.reasonSelectedSaved;

并使用手表我更新了新选择的原因

$scope.$watch('reasonSelected', function () {
        $scope.item.stsChangeReason = $scope.reasonSelected;
    });