在angularjs中记录getelementbyid选项selectedindex

时间:2016-12-01 21:43:53

标签: javascript angularjs

这适用于完美的javascript

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*/
});

1 个答案:

答案 0 :(得分:1)

一种方法是将ng-model属性添加到 select 标记中,然后在范围中设置匹配变量的值(对应于在控制器中设置的范围)。请参阅下面的示例 - 请注意,value属性已添加到选项中。和 tymeJV 一样,ngOptions通常会在角应用程序中用于设置选择标记内的选项节点(请参阅下面的第二个例子)。

&#13;
&#13;
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';
});
&#13;
<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>
&#13;
&#13;
&#13;

使用ngOptions

&#13;
&#13;
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'}
  ];
});
&#13;
<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>
&#13;
&#13;
&#13;