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

+3


source to share


3 answers




+2


source


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"}
    ];  

});

      

+2


source


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

+2


source







All Articles