AngularJS - 从模型中设置选定的值

时间:2017-05-04 10:16:12

标签: javascript angularjs

  

Angular版本 - 1.2.28(旧版,待定升级)

我试图通过模型值为我的select元素设置选定的值。

在我的控制器中,我有以下行;

$scope.customer.country = 'GB';

在我看来,我有以下选择元素;

<select
    ng-model="customer.country"
    ng-options="country as country.name for country in countries track by country.alpha2">
</select>

我当时期待,如果我在alpha2值为&#39; GB&#39;的国家/地区拥有对象,则默认情况下会在渲染时选择该对象。

但实际行为是默认选择空选项。

如何通过模型(ng-model)值设置默认选定值?

1 个答案:

答案 0 :(得分:2)

似乎初始化错误

$scope.customer.country = 'GB';

您必须使用绑定的数组的相同对象进行初始化(国家

应该看起来像

$scope.customer.country = $scope.countries[0];

CodePen