2016-09-16 59 views
2

我已動態創建下拉第一個選項空白。這裏是我的代碼和輸出 -選擇下拉在AngularJs

<select class="form-control" 
    ng-init="option.id = conditions.fieldId" 
    name="conditon_dropdown" 
    ng-model="conditions.fieldId" 
    ng-change="getOptionsChoice(conditions, conditions.fieldId)" 
    ng-options="option.id as option.placeholder for option in attribute_values"> 
</select> 

輸出:

<select ng-options="option.id as option.placeholder for option in attribute_values" ng-change="getOptionsChoice(conditions, conditions.fieldId)" ng-model="conditions.fieldId" name="conditon_dropdown" ng-init="option.id = conditions.fieldId.toString()" class="form-control ng-pristine ng-untouched ng-valid ng-not-empty"> 
    <option value="?" selected="selected"></option> 
    <option label="Size" value="number:1">Size</option> 
    <option label="Color" value="number:2">Color</option> 
    <option label="Fit" value="number:3">Fit</option> 
    <option label="Rise" value="number:4">Select Rise</option> 
</select> 

這裏被自動創建<option value="?" selected="selected"></option>我要選擇我的默認第一個選項<option label="Size" value="number:1">Size</option>

編輯:我已經寫$scope.conditions.fieldId = 1這是工作精細。但我的選擇價值動態。它可能是字符串或整數。如何在沒有控制器的情況下在HTML中進行管

+0

看看http://stackoverflow.com/questions/17968760/how-to-set-a-selected-option-of-a-dropdown-list-使用控制角向-JS – tratto

回答

2

將您的數組的第一個元素到NG-模型元素,這樣

如果陣列是attribute_values

$scope.ngModelElement = $scope.attribute_values[0].fieldId; 

,並確定在控制器ng-model元素與$scope

2

您需要將您的初始模型值設置爲實際對象。

查看工作示例。

// Set by default the value "carton" 
$scope.selectedUserProfile= $scope.userProfiles[0]; 

var myApp = angular.module('myApp',[]); 
 

 
function myCtrl ($scope) { 
 
    $scope.userProfiles = [ 
 
    {id: 10, name: 'Carton'}, 
 
    {id: 27, name: 'Bernard'}, 
 
    {id: 39, name: 'Julie'}, 
 
    ]; 
 
    
 
    // Set by default the value "carton" 
 
    $scope.selectedUserProfile= $scope.userProfiles[0]; 
 
    
 
    $scope.userProfiles1 = [ 
 
    {id: 10, name: 'Carton'}, 
 
    {id: 27, name: 'Bernard'}, 
 
    {id: 39, name: 'Julie'}, 
 
    ]; 
 
};
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<div ng-app="myApp" ng-controller="myCtrl"> 
 
    Dropdown with first option selected 
 
    <select id="requestorSite" ng-model="selectedUserProfile" ng-options="userProfile as userProfile.name for userProfile in userProfiles"> 
 
    </select> 
 
    <br/><br/> 
 
    
 
    Dropdown with first option as blank 
 
    <select id="requestorSite1" ng-model="selectedUserProfile1" ng-options="userProfile as userProfile.name for userProfile in userProfiles1"> 
 
    </select> 
 
    </div>