2016-03-04 88 views
1
[ 
     ... 
     { 
     "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來遍歷它?

問候

回答

1

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]; 
}; 
1

如果你能調整你每天的對象,名稱爲鍵和名稱作爲值的列表,你可以很容易地做到這一點。

重構:

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