使用 Angular 在 select 下拉列表中设置默认值

Set a default value in a select dropdown using Angular

我这里有一个简单的下拉菜单。
默认情况下,我需要将 Tobias 显示为 selected.How 才能做到这一点?

<body>

<div ng-app="myApp" ng-controller="myCtrl">
<select ng-model="selectedName" ng-options="x for x in names">
<option selected="selected">Tobias</option>
</select>
</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.names = ["Emil", "Tobias", "Linus"];
});
</script>

</body>

这就是我在原始代码中尝试的内容。

<select><option value="" selected="selected">{{data.LeaveType}}</option><option data-ng-repeat="data in leaveTypes" value="{{data.id}}">{{data.Name}}</option></select>

//这里data.LeaveType是另一种方法(从后端获取选择的选项)
//data in leaveTypes - 加载下拉数据

只需使用 ng-init 设置默认值

<select ng-model="selectedName" ng-init="selectedName=='Tobias'" ng-options="x for x in names">

演示

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.names = ["Emil", "Tobias", "Linus"];
});
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Hello AngularJS</title>
</head>

<body ng-controller="myCtrl">     
<select ng-model="selectedName" ng-init="selectedName='Tobias'"
ng-options="x for x in names"></select>
 <script src="https://code.angularjs.org/1.6.1/angular.js"></script>
 </body>
</html>

使用 ng-value

为您的 ng-model 对象设置默认值
<select ng-model="selectedName" ng-value="{{selectedName='Tobias'}}"
ng-options="x for x in names">

您也可以在您的控制器中默认设置 selectedName

$scope.selectedName = 'Tobias';

所以在你看来:

<select ng-model="selectedName" ng-options="x for x in names">

在我看来,它比使用 ng-init 设置视图更干净,以便将逻辑保留在控制器中。

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.selectedName = 'Tobias';
    $scope.names = ["Emil", "Tobias", "Linus"];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="myApp" ng-controller="myCtrl">
    <select ng-model="selectedName" ng-options="x for x in names"></select>
</div>

您可以将您的 ng-model 指定为默认值。

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.names = ["Emil", "Tobias", "Linus"];
    $scope.selectedName="Tobias";
});

工作 Plunker:https://plnkr.co/edit/cVaX1VdwFqAh8MoanNJS?p=preview

我认为您使用的 leaveTypes 值是对象类型,您希望在其中显示名称但 select id,对于此类情况,请使用 ngOptions 而不是 ngRepeat

并如下修改你的select,我已经为 Tobias

分配了 id 2
<select ng-model="selectedName" ng-init="selectedName=2" ng-options="data.id as data.name for data in leaveTypes"></select> 

请检查下面的plunker以获得演示

https://plnkr.co/edit/GWsXGohTr6jvG67CY00D?p=preview