Angularjs populate select options with json
I want to populate a select option with values ββfrom the underlying json array.
The example I have is country selection. Each country has an id element and a name plus other fields that I can ignore. Basically, I would like to say that one value in the field value=""
and another between<option>tags</option>
html snippet
<div ng-controller="DemoCtrl">
<p>populate select options with ajax</p>
<select id="Country" name="Country" class="form-control" size="10"
ng-model ="chooseCountries">
<option ng:repeat="country in chooseCountries" value="{{country.id}}">
{{country.name}}
</option>
</select>
</div>
javascript snippet
'use strict';
function DemoSelectCtrl($scope) {
$scope.chooseCountries=[
{countryId : 1, name : "France - Mainland", desc: "some description" },
{countryId : 3, name : "Gibraltar", desc: "some description"},
{countryId : 3, name : "Malta", desc: "some description"}
];
});
I put it together here js fiddle .. I think I am missing something
source to share
-
angular.module('ui.bootstrap.demo', ['ui.bootstrap'])
- make sure you have ui.bootstrap. Read how to install it http://angular-ui.github.io/bootstrap/ - Here is your updated jsfiddle http://jsfiddle.net/e31k5e6L/1/
source to share
You missed an attribute value
, change it to country.countryId
.
Also, set the ng-model
directive to a single countryId value (or an array of country IDs) instead of a full object.
<select id="Country" name="Country" ng-model ="selectedValue">
<option ng:repeat="country in chooseCountries" value="{{country.countryId}}">
...
JS:
function DemoSelectCtrl($scope) {
$scope.selectedValue = 1;
$scope.chooseCountries=[
{countryId : 1, name : "France - Mainland", desc: "some description" },
{countryId : 3, name : "Gibraltar", desc: "some description"},
{countryId : 3, name : "Malta", desc: "some description"}
];
});
source to share
In the above example, you are missing the attribute value
to change this value="{{country.countryId}}"
. try it
<select id="Country" name="Country" class="form-control" size="10" ng-model ="chooseCountries">
<option ng:repeat="country in chooseCountries" value="{{country.countryId}}">
{{country.name}}
</option>
</select>
and see example click here
source to share