'How to auto-fill Dropdown in AngularJs?

I need to make a form where I am having one field which is Gender as dropdown I already have some data I need to auto select my dropdown value based on the data I am getting from the api.

Here is my code ->

<label for="particle1" class="font-weight-bold">Gender : <span class="text-danger">*</span></label>
<select class="form-control" ng-model="patient.gender" ng-init="patient.gender" ng-change="selectGender(patient.gender)">
 <option value="Male">Male</option>
 <option value="Female">Female</option>
 <option value="Others">Others</option>
 </select>

 $scope.patient={
  "firstName" : $scope.patientData.account.firstName,
  "lastName" : $scope.patientData.account.lastName,
  "dob":$scope.patientData.birthDate,
  "gender":$scope.patientData.gender,
   };

$scope.selectGender=(e)=>{
     console.log("Gender",e);
      $scope.patient.gender=e;
   }

However this works for normal input text fields but not working with dropdown. I also want to ask if this is the correct way to get gender by making a new function! can we optimize it so there will be less number of functions How can I dot this? please help



Solution 1:[1]

Here's an example. You can use ng-options to populate your select menu and whenever you need to manually assign a value, just set the object you're using in ng-model. To simulate the API experience, I put in a timeout for 1.5 seconds before it sets the value.

angular.module('myApp', [])
  .controller('myCtrl', ['$scope', '$timeout', function($scope, $timeout) {
    $scope.patient = {}
    $scope.genders = [{
      key: "Male",
      value: "Male"
    }, {
      key: "Female",
      value: "Female"
    }, {
      key: "Others",
      value: "Others"
    }]

    $timeout(function() {
      $scope.patient.gender = "Female";
    }, 1500);
  }]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
  <label for="particle1" class="font-weight-bold">Gender : <span class="text-danger">*</span></label>
  <select class="form-control" ng-model="patient.gender" ng-options='option.key as option.value for option in genders'>
    <option></option>
  </select>

  <p> Selected gender is : {{patient.gender}}</p>
</div>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kinglish