JayIsTooCommon
JayIsTooCommon

Reputation: 1714

AngularJS - Set selected value from model

Angular version - 1.2.28 (Legacy, pending upgrade)

I'm trying to set the selected value for my select element via the model value.

In my Controller I have the below line;

$scope.customer.country = 'GB';

And in my view I have the below select element;

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

I was expecting, that should I have an object in countries with the alpha2 value of 'GB', it would be selected by default on render.

However the actual behaviour is the empty option is selected by default.

How do I set the default selected value via the model (ng-model) value?

Upvotes: 0

Views: 70

Answers (1)

mastermind
mastermind

Reputation: 1057

It seems initialization is wrong

$scope.customer.country = 'GB';

You have to initialize with the same object of array which is binded (countries)

should look like

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

CodePen

Upvotes: 2

Related Questions