Angularjs populate select options with json
35,760
Solution 1
-
angular.module('ui.bootstrap.demo', ['ui.bootstrap'])
- be 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/
Solution 2
In this above example you are missing value
attribute change this value="{{country.countryId}}"
. try this
<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 the example click here
Solution 3
You miss-typed the value
attribute, change it to country.countryId
.
Also, set ng-model
directive to a single countryId value (or array of country IDs) instead of the 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"}
];
});
Related videos on Youtube
Author by
Robbo_UK
Updated on July 30, 2022Comments
-
Robbo_UK almost 2 years
I am looking to populate select option with values from a basic json array.
The example I have is a country select. Each country has an id element and a name plus other fields that I can ignore. Basically I would like to say put one value in the
value=""
field and another between the<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 have put it together here js fiddle.. I think I'm missing something
-
vamsikrishnamannem over 9 yearschange the value of option
value="{{country.countryId}}"
-
Wtower over 7 yearsIt is better advised to use
ng-options
.
-
-
Robbo_UK over 9 yearswhat is this line doing?
$scope.selectedCountry = angular.copy($scope.chooseCountries[0]);
-
user2700840 over 9 yearsIt's just default value for $scope.selectedCountry (you can remove this line if you don't want to use default value). In this case angular.copy creates copy of first element of chooseCountries array. So it means $scope.selectedCountry = {countryId : 1, name : "France - Mainland", desc: "some description" };