Search code examples
javascriptangularjsng-options

While generating dropdownlist with ng-options, how to set the selected option?


Here is the plnker demo

In the script.js, I create a variable info to store the options. The selected option should be "Spanish" because,

 {
     "name": "Spanish", 
     "value": 3082, 
     "selected": true //It's true here.
 }

How to solve this problem?


Solution

  • You need to add the ng-model. Based on your info.value.lang you can set the selected : true to the model value.

    function MyCntrl($scope) {
        $scope.info = info;
        $scope.selectedItem = null;
    
        angular.forEach(info.value.lang, function(lang) {
          if (lang.selected === true){
            $scope.selectedItem = lang.value;
          }
        });
    }
    
    <div ng-controller="MyCntrl">
      <select ng-model="selectedItem" ng-options="option.value as option.name for option in info.value.lang" >
      </select>
    </div>
    

    Demo : http://plnkr.co/edit/RMr19uwuOH3EEjMd7cRL