Reputation: 935
I have a array of objects like following, I would like show in select tag using ng-options.
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
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