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

标签 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 的列表
  • 第二个显示来自所选城市的所有人姓名的列表。

我还想将所选用户名的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>

最佳答案

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

关于javascript - 使用 AngularJS 使用对象数组填充和过滤下拉列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41117227/

相关文章:

javascript - 如何在不旋转的情况下以圆周运动移动图像?

javascript - 使用 $.getjson 从外部源请求 JSON。 200成功但它在哪里?

javascript - React onmouseover 在另一个 div 中获取内容

javascript - 使用 Javascript 修改 css 类不起作用

html - Django 没有加载 CSS?

AngularJS : how to refresh object without data loss?

javascript - 导航栏悬停效果 - CSS

html - jsp中如何上传多个文件?

angularjs - 使用 WebAPI 对 ng-grid 进行服务器端分页+过滤+排序

javascript - 自定义指令中 Angularjs 范围的使用