使用AngularJS使用对象数组填充和过滤下拉列表

时间:2016-12-13 09:11:34

标签: javascript html angularjs

我有以下来自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" }
]
}]

我正在尝试设置两个下拉列表:

  • 第一个显示cityNames
  • 的列表
  • 第二个显示所选城市中所有人names的列表。

我还想将所选用户名的id保存到变量中。

到目前为止我已经尝试过了:

<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>

1 个答案:

答案 0 :(得分:3)

您应该使用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.