Javascript 使用带有角度的ng选项显示带有键和值的选择选项,并设置默认值

Javascript 使用带有角度的ng选项显示带有键和值的选择选项,并设置默认值,javascript,angularjs,angularjs-ng-options,Javascript,Angularjs,Angularjs Ng Options,我有以下json: [ {"country": "United States", "code": "US"}, {"country": "Canada", "code": "CA"}, {"country": "Mexico", "code": "MX"} ] 在我看来,我有 <select ng-model="selectedCountry" name="selectedCountry" id="selectedCountry" ng-options="co

我有以下json:

[
    {"country": "United States", "code": "US"},
    {"country": "Canada", "code": "CA"},
    {"country": "Mexico", "code": "MX"}
 ]
在我看来,我有

 <select ng-model="selectedCountry" name="selectedCountry" id="selectedCountry" ng-options="country.country as country.country for country in countries" ng-change="onCountryChange()" required></select>


是否有人知道如何解决此问题。

使用
track by
表达式,您可以忽略任何其他属性并按如下方式设置默认值:

$scope.selectedCountry = { code: "CA" };
<select ng-model="selectedCountry" name="selectedCountry" id="selectedCountry" ng-options="country.code as country.country for country in countries" ng-change="onCountryChange()" required></select>
希望这有帮助

编辑:如果您希望
$scope.selectedCountry
的值只是一个字符串(即“US”、“CA”或“MX”),则无需使用
跟踪方式
,您可以使用
ng选项
,如下所示:

$scope.selectedCountry = { code: "CA" };
<select ng-model="selectedCountry" name="selectedCountry" id="selectedCountry" ng-options="country.code as country.country for country in countries" ng-change="onCountryChange()" required></select>


示例Plunker:

这似乎可行,但我注意到,当我更改默认国家/地区时,它会创建一个新的国家/地区,这是因为您的
ng options
表达式与track by不兼容。您希望
$scope.selectedCountry
的预期值是多少?我希望它是美国、CA或MXWorks Perfect谢谢您的帮助
$scope.selectedCountry = { code: "CA" };
<select ng-model="selectedCountry" name="selectedCountry" id="selectedCountry" ng-options="country.code as country.country for country in countries" ng-change="onCountryChange()" required></select>