angularjsangularjs-select2angularjs-material

How can pre-load the value in Angular material select?


I want to pre-load the value in md-select

I have the following code

<md-select ng-model="country" ng-model-options="{trackBy: '$value.code'}" >
    <md-optgroup label="Country">
        <md-option ng-value="country" ng-repeat="country in countries">
                    {{country.name}}
        </md-option>
    </md-optgroup>
</md-select>

Controller

 $scope.country = "usa"; //I will receive only the key from the server side 
                         //in the response object

$scope.countries = [{"code":"usa","name":"United States of America"},
  {"code":"ind","name":"India"},
  {"code":"eng","name":"England"},    
  {"code":"aus","name":"Australia"}];

Here I want to load "United States of America" initially.

This is currently not working.


Solution

  • Assume your service returns the key "usa", it checks for the existence of key in the drop down array and assign the object to the $scope.country,

    app.controller('myCtrl', function($scope) {
     $scope.service = "usa";
    $scope.countries = [{"code":"usa","name":"United States of America"},
      {"code":"ind","name":"India"},
      {"code":"eng","name":"England"},    
      {"code":"aus","name":"Australia"}];
    
       angular.forEach($scope.countries, function(value) {
            if (value.code === $scope.service ) {
                $scope.country ={code: $scope.service , name: value.name};
                console.log($scope.country);
            }
        });
    
    });
    

    WORKING DEMO