1

This works in perfect javascript

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

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

How do you do this same but in Angularjs

app.controller("BodyController",function($scope){
/****************codeeeeeeeeeeeeeeeeeeeeeeeeee*/
});
  • You would use `ngOptions` with your select and set the `ngModel` to the option you want selected. And you can use the exact same code (it'd just be the complete wrong way of doing it in Angular, but it would work... because Angular is JavaScript) – tymeJV Dec 01 '16 at 21:45
  • Possible duplicate of [AngularJS Select element set the selected index](http://stackoverflow.com/questions/26217067/angularjs-select-element-set-the-selected-index) – Sᴀᴍ Onᴇᴌᴀ Dec 01 '16 at 21:47

1 Answers1

1

One way is to add the ng-model attribute to the select tag, and then set the value of the matching variable in the scope (corresponding to the scope set in the controller). See the example below - bear in mind that value attribute were added to the options. And like tymeJV mentioned, ngOptions would typically be used in an angular application to set the option nodes inside the select tag (see the second example below).

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>

Using 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>
Sᴀᴍ Onᴇᴌᴀ
  • 8,218
  • 8
  • 36
  • 58