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

2 Answers 2

1

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];
};
Sign up to request clarification or add additional context in comments.

Comments

1

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.