默认有条件选择下拉值

By default Selecting dropdown value conditionally

本文关键字:选择 有条件 默认      更新时间:2023-09-26

我有2个选项Month & Year下拉。根据API调用响应,如果period == Y,年份默认选择&如果是period == M,则选择"Month"。我不知道该怎么做。

<div class="col-sm-3 PDL dateY">
    <select class="form-control" id="sel1" ng-model="SelectedValue_free" ng-options="details.period for details in validity_dd">
    </select>
</div>    
 $scope.validity_dd = [
    {
        period: 'Year'
    }, {
     period: 'Month'
    }
]   

根据您从api获取信息后的情况,设置

 if(period == 'Y') 
 $scope.SelectedValue_free= 'Year';
 else if(period == 'M') 
 $scope.SelectedValue_free= 'Month';

将ng-options更改为

 ng-options="details.period as details.period for details in validity_dd"

或者您可以设置

 if(period == 'Y') 
 $scope.SelectedValue_free= $scope.validity_dd[0];
 else if(period == 'M') 
 $scope.SelectedValue_free= $scope.validity_dd[1];

ng-options="details.period for details in validity_dd"

在app.js中使用以下脚本

$scope.validity_dd = [
    {
        period: 'Year'
    }, {
     period: 'Month'
    }
]   
//this is an array to store all the possible options as key value pairing
$scope.opt_arr={'Y':'Year','M':'Month'};
//Here you can set the value of period with api call response data
$scope.period='M';
//this will search the object from the array which match the data
var result = $.grep($scope.validity_dd, function(e)
            { return e.period == $scope.opt_arr[$scope.period]; });
//this will set the model value so that the required option will be selected
$scope.SelectedValue_free=result[0];