简体   繁体   中英

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

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 .

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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