Search code examples
htmlangularjsselectng-optionsselected

setting selected tag when ng-option is used


I have this code which loads the value into drop down list through ng-option. But I am unable to set the default value when I use ng-option. Please find my code here and help me with this.

               <div class="form-group">
                    <label class="control-label col-lg-2 pull-left">Quality<span class="Imp">*</span></label>
                          <div class="col-lg-8">
                 <select id="Quality" name="Quality" class="form-control" style="width:170px" ng-options="Q.value as Q.name for Q in vm.quality" ng-model="vm.Edit.Quality" tooltip="Quality is required"
                  tooltip-placement="top" required>

                             </select>
                        </div>
                  </div>

the angular code is here:

 vm.quality = [{ value: 'Satisfactory', name: "Satisfactory" },
        { value: 'NotSatisfactory', name: "Not Satisfactory" }];
        vm.Edit.Quality = vm.quality[0];

I have used last line vm.Edit.Quality = vm.quality[0];to set the selected(default) value to quality which is not working.


Solution

  • Try like this

    var app = angular.module('anApp', []);
    app.controller('aCtrl', function($scope) {
    var vm = this;
       vm.quality = [{ value: 'Satisfactory', name: "Satisfactory" },
            { value: 'NotSatisfactory', name: "Not Satisfactory" }];
            vm.Quality = vm.quality[0].value;
    })
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
    
    <div ng-app="anApp" ng-controller="aCtrl as vm">
     <div class="form-group">
         <label class="control-label col-lg-2 pull-left">Quality<span class="Imp">*</span></label>
         <div>
          <select ng-options="Q.value as Q.name for Q in vm.quality"
                       ng-model="vm.Quality">
          </select>
        </div>
      </div>
    </div>