2016-09-07 150 views
0

我有一個下拉選項和2個選項Month & Year。基於API調用響應,如果,Year應該被選中默認&如果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' 
    } 
] 
+0

您的下拉菜單中有空值嗎? – VjyV

+0

由於ng-model變量沒有在js文件中聲明,所以變爲null。 – VjyV

回答

0

根據您的情況您瞭解從API的信息後,設置

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

更改您NG-選項,

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" 
+0

下拉選項中有一個空白選項。沒有值被選中。 – srv

+0

嘗試更改ng選項表達式 – Hmahwish

0

在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];