2016-12-01 52 views
1

這工作在完善的JavaScript的SelectedIndex文檔的getElementById選項angularjs

document.getElementById("mySelect").selectedIndex = "0" 

<select class="selectpicker" id="mySelect"> 
    <option>English &nbsp;</option> 
    <option>Español &nbsp;</option> 
</select> 

你如何做到這一點相同,但Angularjs

app.controller("BodyController",function($scope){ 
/****************codeeeeeeeeeeeeeeeeeeeeeeeeee*/ 
}); 
+0

你會使用'ngOptions'您選擇並設置'ngModel'您要選擇的選項。你也可以使用完全相同的代碼(它剛剛在角做的完全錯誤的方式,但它的工作...因爲角是JavaScript的) – tymeJV

+0

的可能的複製[AngularJS選擇元素設置所選指數( http://stackoverflow.com/questions/26217067/angularjs-select-element-set-the-selected-index) –

回答

1

一種方法是添加ng-model屬性到選擇標記,然後在範圍(對應於控制器設定的範圍)設置的匹配變量的值。見下面的例子 - 記住,value屬性添加到選項熊。而像tymeJV提到的,ngOptions通常以成角度的應用程序中使用的選項設置的選擇標籤內節點(見下面的第二個例子)。

angular.module('app',[]) 
 
.controller("BodyController",function($scope){ 
 
    //set the model value to 'en', so the select list will select the option with value=='en' 
 
    $scope.lang = 'en'; 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<div ng-app="app" ng-controller="BodyController"> 
 
<select class="selectpicker" id="mySelect" ng-model="lang"> 
 
    <option value="en">English &nbsp;</option> 
 
    <option value="es">Español &nbsp;</option> 
 
</select> 
 
</div>

使用ngOptions

angular.module('app',[]) 
 
.controller("BodyController",function($scope){ 
 
    //set the model value to 'en', so the select list will select the option with value=='en' 
 
    $scope.lang = {name: 'English', id: 'en'}; 
 
    $scope.langs = [ 
 
     {name: 'English', id: 'en'}, 
 
     {name: 'Español', id: 'es'} 
 
    ]; 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<div ng-app="app" ng-controller="BodyController"> 
 
<select class="selectpicker" id="mySelect" ng-model="lang" ng-options="lang.name for lang in langs track by lang.id"> 
 
</select> 
 
</div>

+0

THX ..♥............... –