我在这里有一个简单的下拉菜单。
默认情况下,我需要将Tobias
显示为已选中。如何做?
<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
- 加载下拉数据
答案 0 :(得分:3)
只需使用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>
答案 1 :(得分:2)
我认为你使用的leaveTypes值是对象类型,你要显示名称但是选择id,对于这些场景,使用ngOptions而不是ngRepeat
并修改您的选择如下,我为Tobias指定了ID 2
<select ng-model="selectedName" ng-init="selectedName=2" ng-options="data.id as data.name for data in leaveTypes"></select>
请查看下面的plunker进行演示
答案 2 :(得分:1)
使用ng-model
ng-value
对象设置默认值
<select ng-model="selectedName" ng-value="{{selectedName='Tobias'}}"
ng-options="x for x in names">
答案 3 :(得分:1)
您还可以在控制器中默认设置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>
答案 4 :(得分:1)
您可以将ng-model指定为默认值。
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.names = ["Emil", "Tobias", "Linus"];
$scope.selectedName="Tobias";
});
Working Plunker :https://plnkr.co/edit/cVaX1VdwFqAh8MoanNJS?p=preview