Durga Prasad
Durga Prasad

Reputation: 935

ng-options default option object is not selecting with an array of objects

I have a array of objects like following, I would like show in select tag using ng-options.

  1. I have to show country name as display name
  2. I have compulsory Store selected 'object' in model option

for default option

In controller

$scope.selectedCountry = {"US":"United States"}
$scope.countries: [
   {"name":"United States", code: "US"},
   {"name":"Canada", code: "US"},
   {"name":"Afghanistan", code: "US"},
   {"name":"Albania", code: "US"},
   {"name":"Algeria", code: "US"},
   {"name":"American Samoa", code: "US"},
      .....
   ];

In html page:

ng-model="selectedCountry" ng-options="country as country.name for country in countries track by country"

It is not selecting default object

can you please suggest what is wrong ?

Thanks in Advance, Prasad.

Upvotes: 0

Views: 112

Answers (1)

Alfonso Presa
Alfonso Presa

Reputation: 1034

You should set the default like this:

$scope.countries= [
   {"name":"United States", code: "US"},
   {"name":"Canada", code: "C"},
   {"name":"Afghanistan", code: "A"},
   {"name":"Albania", code: "AL"},
   {"name":"Algeria", code: "AG"},
   {"name":"American Samoa", code: "AS"}
];
$scope.selectedCountry = $scope.countries[1]; //Select Canada

Also you need to remove the track by.

Here you have a working example:

http://plnkr.co/edit/kkq0Fy4NCfBIa0Ioy8En?p=preview

Also here you have another example if you prefer selecting by country code (wich seems cleaner to me):

http://plnkr.co/edit/TaCcpgtMLYFvzQqcdGKS?p=preview

Upvotes: 1

Related Questions