How to handle cascading/chained dropdowns using multiple ng-options

后端 未结 1 992
小蘑菇
小蘑菇 2020-12-22 02:57

I am trying to get drop downs to only populate if the drop down above them has something selected. I had someone point me in the right starting direction with something like

相关标签:
1条回答
  • 2020-12-22 03:50

    I would probably try avoid repeating by rearranging the data and tweak the logic a bit. I would just have one select with ng-repeat and my source data will be a 2D array.

    Example:-

    //It does not matter where i get the data from 
    $scope.selects = [[{name:'level11', id:1}, {name:'level12', id:2}, {name:'level13', id:3}], 
        [{name:'level21', id:1}, {name:'level22', id:2}, {name:'level23', id:3}],
        [{name:'level31', id:1}, {name:'level32', id:2}, {name:'level33', id:3}],
        [{name:'level41', id:1}, {name:'level42', id:2}, {name:'level43', id:3}],
        [{name:'level51', id:1}, {name:'level52', id:2}, {name:'level53', id:3}]];
    

    Then i would just keep an array to store respective models:-

    $scope.selected = Array.apply(null, { length: $scope.selects.length }).map(Object); 
    

    Then have just one changehandler for all of them, which currently pass index you could even pass data.

     $scope.handleChange = function(index) {
         //reset data for others when a dropdown in selected
         $scope.selected = $scope.selected.map(function(itm, idx){
               return (idx > index) ? {} : itm;
         });
    
        //This will give you selected value of the current item if you need
        var selected = $scope.selected[index];
        //DO something with the value
      }
    

    And finally my markup would just be:-

    <select ng-repeat="select in selects" ng-class="selectLevel{{$index}}"
             ng-change='handleChange($index)' <!-- Handler for Change event pass index of even model -->
             ng-model='selected[$index].value' <!-- Yes this is the model -->
             ng-show='!$index || selected[$index-1].value' <!-- Show only if its previous model has a value -->
             ng-options='obj.name for obj in select track by obj.id'>
    </select>
    

    Demo

    0 讨论(0)
提交回复
热议问题