如何迭代“ng-options”属性中的对象内的数组?

问题描述:

[ 
     ... 
     { 
     "surname":"Williams" 
     "name":['Holly','James','Robert','Kim'] 
     }, 
     { 
     "surname":"Jones" 
     "name":['Holly','Joe','Jon','Harry'] 
     } 
     ... 
    ] 

如果我有2个下拉菜单。第二个依赖于第一个。如何迭代“ng-options”属性中的对象内的数组?

第一个下拉列表中填写姓氏。

<select ng-model="surnameSelect" ng-options="person.surname as person.surname for person in persons"> 
 
    <option value="" ng-if="!surnameSelect"></option> 
 
</select>

现在基于所选择的“姓”,我要填充与来自其中姓选择的姓相匹配的对象的阵列中的值的第二个下拉。

我的问题是这样的。我怎样才能找到该数组,以及如何使用angularJS中的ng-options来遍历它?

问候

Here是Plunker与可能的解决方案:在surname select执行ng-change="populate()"

<select ng-change="populate()" ng-model="surnameSelect" ng-options="person.surname as person.surname for person in persons"></select> 

<select ng-model="nameSelect" ng-options="name as name for name in currentNames"></select> 

查看plunker中的完整实现。

$scope.populate = function(){ 
    var currentPerson = $scope.persons.filter(function(person) { 
    return person.surname == $scope.surnameSelect; 
    }); 
    $scope.currentNames = currentPerson[0].name; 
    $scope.nameSelect = $scope.currentNames[0]; 
}; 

如果你能调整你每天的对象,名称为键和名称作为值的列表,你可以很容易地做到这一点。

重构:

$scope.data = persons.reduce(function(p, c) { 
    if (!p.hasOwnProperty(c.surname)) { 
     p[c.surname] = p.name; 
    } 

    return p; 
}, {}); 

并使用新的结构:

<select ng-model="selectedSurname" ng-options="surname as surname for (surname, names) in data"></select> 
<select ng-model="selectedName" ng-options="name as name for name in data[selectedSurname]"></select>