Skywalker
Skywalker

Reputation: 5194

Populate and filter a dropdown with an array of objects using AngularJS

I have the following data structure thats coming from an API.

$scope.cityList = [{
"_id": {
    "$oid": "584ebd7f734d1d55b6dd4e5e"
},
"cityName": "New York",
"region": "north",
"people": [
    { "id": 1, "name": "x" },
    { "id": 2, "name": "y" },
    { "id": 3, "name": "z" },
    { "id": 4, "name": "a" },
    { "id": 5, "name": "b" },
    { "id": 6, "name": "c" }
]
},
{
"_id": {
    "$oid": "584ebd7f734d1d55b6dd4e5e"
},
"cityName": "New Jersey",
"region": "South",
"people": [
    { "id": 1, "name": "x" },
    { "id": 2, "name": "y" },
    { "id": 3, "name": "z" },
    { "id": 4, "name": "a" },
    { "id": 5, "name": "b" },
    { "id": 6, "name": "c" }
]
}]

I'm trying to setup two dropdowns:

I also want to save the id of the selected user name into a variable.


I've tried this so far:

<select ng-model="city">
    <option ng-repeat="city in cityList" value="{{city.cityName}}">{{city.cityName}}</option>
</select>

<select ng-model="selectedItem">
    <optgroup ng-repeat="option in cityList | filter: city">
        <option ng-repeat="x in option.people">{{x}}</option>
</select>

Upvotes: 3

Views: 1182

Answers (1)

Mistalis
Mistalis

Reputation: 18279

You should use ng-options:

<select ng-model="selectedCity" 
        ng-options="c as c.cityName for c in cityList">
</select>

<select ng-model="selectedPerson" 
        ng-options="p as p.name for p in selectedCity.people">
</select>

Demo on JSFiddle.

Upvotes: 3

Related Questions