Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • the first one displays a list of the cityNames
  • the second displays the list of all people names from the selected city.

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>
like image 524
Skywalker Avatar asked Dec 03 '25 16:12

Skywalker


1 Answers

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.

like image 177
Mistalis Avatar answered Dec 06 '25 05:12

Mistalis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!