gpt4 book ai didi

javascript - 如何使用多个 ng-options 处理级联/链接下拉菜单

转载 作者:行者123 更新时间:2023-11-30 17:19:28 25 4
gpt4 key购买 nike

我正在尝试让下拉菜单仅在下拉菜单中选择了某些内容时才填充。有人用这样的东西给我指出了正确的开始方向。

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

这对第一轮没问题 - 在前一个选择了某些内容之前,下面的下拉列表不会填充。棘手的部分是我试图弄清楚是否说我一直选择到第 5 级,然后重新选择第 2 级。然后我希望第三层出现,而 4-5 层消失。我在想也许像 ng_show="!scope2 || !scope3"这样的东西(或者我传递多个参数的类似东西),但我似乎无法让这样的东西在 Angular 上工作。有没有更好的方法来处理这个问题?

最佳答案

我可能会尝试通过重新排列数据并稍微调整逻辑来避免重复。我只想用 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

关于javascript - 如何使用多个 ng-options 处理级联/链接下拉菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25413071/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com