[英]How to iterate through an array inside object in “ng-options” attribute?
[
...
{
"surname":"Williams"
"name":['Holly','James','Robert','Kim']
},
{
"surname":"Jones"
"name":['Holly','Joe','Jon','Harry']
}
...
]
如果我有2個下拉菜單。 第二個依賴於第一個。
第一個下拉列表中填有姓氏。
<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遍歷該數組?
最好的祝福
如果您可以將一天的結構重組為一個對象,而名稱是鍵,名稱列表是值,那么您可以輕松實現。
重組:
$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>
這是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];
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.