如何使用多个ng-options处理级联/链式下拉列表

时间:2014-08-20 19:37:09

标签: javascript html angularjs angularjs-scope angularjs-ng-options

我试图让下降只是填充,如果他们上面的下拉选择了某些东西。我有人用正确的方式指出了我的正确方向。

<select class="selectLevel0" ng-model='scope1' ng-change='scope1Change()' 
        ng-options='obj.name for obj in array track by obj.id'>
</select>

<select class="selectLevel1" ng-model="scope2"  ng-change='scope2Change()' 
        ng-options='obj.name for obj in array2 track by obj.id' ng-hide='!scope1'>
</select>

<select class="selectLevel2" ng-model="scope3" ng-change='scope3Change()' 
        ng-options='obj.name for obj in array3 track by obj.id' ng-hide='!scope2'>
</select>

<select class="selectLevel3" ng-model="scope4" ng-change='scope4Change()' 
        ng-options='obj.name for obj in array4 track by obj.id' ng-hide='!scope3'>
</select>

<select class="selectLevel4" ng-model="scope5" 
        ng-options='obj.name for obj in array5 track by obj.id' ng-hide='!scope4'>
</select>

这对于第一轮来说没问题 - 下面的下降将不会填充,直到前一个选择了某些东西。棘手的部分是我试图弄清楚是否说我已经选择了一直到第五级,我重新选择了第二级。然后我想要第三级出现,4-5要消失。我想的可能就像ng_show =&#34;!scope2 || !scope3&#34; (或类似的地方,我传递多个参数),但我似乎无法得到像这样的角度工作。有没有更好的方法来解决这个问题?

1 个答案:

答案 0 :(得分:2)

我可能会尝试通过重新排列数据并稍微调整逻辑来避免重复。 我只有一个选择ng-repeat,我的源数据将是2D数组。

实施例: -

//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}]];

然后我会保留一个数组来存储各自的模型: -

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

然后只有一个changehandler用于所有这些,当前通过索引甚至可以传递数据。

 $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
  }

最后我的标记就是: -

<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