Question

I want to populate a dropdown with an array, and if the user chooses an option that has a nested array, Then and only then I want to show another dropdown and populate it with that child array, and so on.

And then populate a hidden field with the last value of the chain.

How would I approach this with Angular.js?

Was it helpful?

Solution

You can use ng-show to conditionally show/hide the second drop-down

The code can be seen/tested here

Controller:

app.controller('MainCtrl', function($scope) {
  $scope.items = [
    {name:'item1'},
    {name:'item2', subItems: [
      {name:'sub item 1'},
      {name:'sub item 2'}]}];
});

Markup:

<p>
  <select ng-model="selectedItem" ng-options="i.name for i in items"></select>
</p>
<p ng-show="selectedItem.subItems">
  <select ng-model="selectedSubItem" ng-options="i.name for i in selectedItem.subItems"></select>
</p>

OTHER TIPS

Use ng-change directive in your select tag and in ng-change call a function that checks your scenario.

If you provide your array data, the answer can be given more accurately.

I know this approach is a long run. But it helps you to keep your code clean.

MARKUP

<select ng-model="selectedItem" ng-options="item.name for item in items" ng-change="doesItemHaveSubArray(selectedItem)"></select>

<div ng-if="subItem">
  <select ng-model="selectedSubItem" ng-options="item.name for item in subItem"></select>
</div>

In JS

$scope.doesItemHaveSubArray=function(item){
        if(item!==undefined){
          $scope.subItem=item.subItems;
        }
      }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top