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

后端 未结 1 1003
小蘑菇
小蘑菇 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:-

    
    

    Demo

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