简体   繁体   English

如何遍历“ ng-options”属性中对象内部的数组?

[英]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']
      }
      ...
   ]

If I have 2 dropdowns. 如果我有2个下拉菜单。 The second one is dependent on the first one. 第二个依赖于第一个。

The first dropdown is filled with surnames. 第一个下拉列表中填有姓氏。

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

Now based on the "surname" selected, I want to fill the second dropdown with the values from the array from the object where surname matches the surname selected. 现在基于选定的“姓氏”,我想用姓氏与所选姓氏匹配的对象中数组中的值填充第二个下拉列表。

My question is this. 我的问题是这个。 How can I find that array and how can I iterate through it using ng-options in angularJS??? 我如何找到该数组以及如何使用angularJS中的ng-options遍历该数组?

Best Regards 最好的祝福

If you can restructure your day to an object, with the name being the key and the list of names being the values, you can do it easily. 如果您可以将一天的结构重组为一个对象,而名称是键,名称列表是值,那么您可以轻松实现。

Restructure: 重组:

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

    return p;
}, {});

And using the new structure: 并使用新结构:

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

Here is Plunker with possible solution: execute ng-change="populate()" on surname 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>

See full implementation in plunker. 参见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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM