2016-09-07 176 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];