[英]How to display an option by default in <select> if the values are coming dynamically from rest call
我有一个字段,其中的值来自服务,我正在使用ng-options显示在选择字段中。但是默认情况下,我想显示第一个选项。
HTML
<div class="col-lg-4">
<select class="form-control" id="select" ng-model="$root.customerDetails.traderType"
ng-options="traderTypeObj.description for traderTypeObj in traderTypes track by
traderTypeObj.type">
</select>
</div>
js:
if(results.data.traderTypes.status.code == 200){
for(let i= 0; i< results.data.traderTypes.body.length ; i++ ){
let keyVal = {};
keyVal.type = results.data.traderTypes.body[i].ITTD_TRADER_TYPE_CODE;
keyVal.description = results.data.traderTypes.body[i].ITTD_TRADER_TYPE_DESCRIPTION;
$scope.traderTypes.push(keyVal);
}
}
if($rootScope.customerDetails != null &&$rootScope.customerDetails.natureOfBusiness != null && $rootScope.customerDetails.traderType !=
null){
for(let i=0; i < $scope.businessTypes.length ; i++ ){
if($scope.businessTypes[i].description == $rootScope.customerDetails.natureOfBusiness.description){ $rootScope.customerDetails.natureOfBusiness.type =
$scope.businessTypes[i].type;
}
}
for(let i=0; i < $scope.traderTypes.length ; i++ ){
if($scope.traderTypes[i].description == $rootScope.customerDetails.traderType.description){$rootScope.customerDetails.traderType.type = $scope.traderTypes[i].type;
} $rootScope.customerDetails.traderType=$scope.traderTypes[0].description;
}
$scope.$apply();
}}
}
我试图从默认情况下显示第一个选项..任何想法
您可以使用,它会在初始化时将您的第一个选项设置为默认值,
ng-init="$root.customerDetails.traderType = options[0]"
// In HTML
<select class="form-control" id="select" ng-
model="$root.customerDetails.traderType"
ng-options="traderTypeObj.description for traderTypeObj in traderTypes track
by traderTypeObj.type" ng-init="$root.customerDetails.traderType =
options[0]">
使用ng-init
<select class="form-control" id="select" ng-init="$root.customerDetails.traderType = traderTypes[0]" ng-model="$root.customerDetails.traderType"
ng-options="traderTypeObj.description for traderTypeObj in traderTypes track by
traderTypeObj.type">
您可以在模型中保存默认选项值,例如:
<select class="form-control" id="select" ng-model="$root.customerDetails.traderType"
ng-options="traderTypeObj.description for traderTypeObj in traderTypes track by
traderTypeObj.type">
并且在服务存储中,值如下:如果您有id字段,则为0,否则值为“ abc”
$root.customerDetails.traderType = 0;
or
$root.customerDetails.traderType = "abc";
最简单的一个:
<select class="form-control" id="select" ng-model="$root.customerDetails.traderType"
ng-options="traderTypeObj.description for traderTypeObj in traderTypes track by
traderTypeObj.type">
<option value="DefaultOption">Your default option</option>
</select>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.