3

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>
6
  • Where is cityList defined? Commented Dec 13, 2016 at 9:20
  • cityList is the JSON object defined at the beginning. Commented Dec 13, 2016 at 9:24
  • @lin In my angular controller, the data comes from an API and save it in the cityList object. i.e $scope.cityList = dataFromAPI Commented Dec 13, 2016 at 9:25
  • Thanks, that wasn't clear. Coding is not imaging :) You should edit your question. Commented Dec 13, 2016 at 9:25
  • You should normalize your response in JavaScript due to the use case of your dropdown's. Do you need a working example? Commented Dec 13, 2016 at 9:26

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Great +1 KISS!!
This worked perfectly. Thank you. Learned something new today!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.