Bros Code
Bros Code

Reputation: 73

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

Upvotes: 1

Views: 280

Answers (2)

oKonyk
oKonyk

Reputation: 1476

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

Upvotes: 1

tymeJV
tymeJV

Reputation: 104775

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>

Upvotes: 1

Related Questions