2016-09-11 94 views
0

我要預先加載在MD-選擇如何預加載角度材料選擇中的值?

值我有以下代碼

<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> 

控制器

$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"}]; 

在這裏,我要加載「美國「 原來。

目前無法正常工作。幫我完成這件事......

回答

1

假設你的服務返回鍵"usa",它會檢查關鍵的下拉陣列的存在和分配對象到$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

+0

我想只發送選定對象的代碼。 ng-value =「country.code」不預先加載數據。另外選擇不起作用。如果我選擇任意一個國家/地區,請選擇下拉菜單中的最後一個條目。我怎樣才能只發送密鑰 – Prince