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

一笑奈何 提交于 2019-11-29 16:46:33

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!