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

时间:2016-03-04 19:09:02

标签: javascript arrays angularjs

   [
      ...
      {
         "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>

现在基于所选的“姓氏”,我想用第二个下拉列表填写来自surname与所选姓氏匹配的对象的数组中的值。

我的问题是这个。如何找到该数组,如何使用angularJS中的ng-options迭代它?

最好的问候

2 个答案:

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

答案 1 :(得分:1)

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

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