用角方式过滤两个下拉框

Filter Two Dropdowns Based on One Another the Angular Way

本文关键字:两个 方式 过滤      更新时间:2023-09-26

我有两个下拉列表。这些下拉框中允许的选项应该根据其他下拉框中的内容进行过滤。这是第一个下拉列表:

<select ng-model="filter.levelPregenerate">
  <option value="">All</option>
  <option value="assox">Associate's</option>
  <option value="bachx">Bachelor's</option>
  <option value="mastx">Master's</option>
  <option value="doctx">Doctorate</option>
  <option value="nondx">Non-Degree</option>
  <option value="bridx">Bridge</option>
</select>

第二个下拉框为ng-repeat,如下所示:

<select ng-model="filter.degreeTypePregenerate">
  <option value="">All</option>
  <option ng-repeat="type in degreeType | orderBy:'toString()'">{{type}}</option>
</select>

这是上面重复的数组:

$scope.degreeType = ['BA', 'BS', 'MA', 'MBA', 
                     'MDIV', 'MED', 'MFA', 'MPH', 
                     'MS',' DNP', 'EDD', 'PHD', 
                     'EDSPL', 'GRDCERT'];

第一个和第二个下拉框中的选项应该相互过滤。下面是两者之间的映射(过滤器应该如何工作):

assox: '';
bachx: 'BA, BS';
mastx: 'MA, MBA, MDIV, MED, MFA, MPH, MS';
doctx: 'DNP, EDD, PHD';
nondx: 'EDSPL, GRDCERT';
bridx: ''

因此,如果在第二个下拉列表中选择了'BA',那么'bachx'应该是第一个下拉列表中唯一可用的选项。相反,如果' docx '在第一个下拉框中被选中,'DNP', 'EDD'和'PHD'应该是第二个下拉框中唯一可选的选项。

这里有一个完整的代码:http://codepen.io/trueScript/pen/LVZKEo

我不认为我可以简单地应用一个基本的'| filter:foo'到第二个下拉列表,因为它不知道如何过滤它。Angular是怎么做的呢?

您可以设置一个自定义过滤器并返回应该显示的值。有两种方法:

选项1 - If/else

angular.module('programApp', [
    'programApp.controllers',
    'programApp.filters'
]);
angular.module('programApp.filters', [])
.filter('dropdownFilter', function() {
    return function(input, degreeTypePregenerate) {
    if (degreeTypePregenerate === 'assox') {
      return [];
    } else if (degreeTypePregenerate === 'bachx') {
      return ['BA', 'BS'];
    }
    // and so on..
    }
});

选项2 -一个对象(我认为是cleaner)

angular.module('programApp.filters', [])
.filter('dropdownFilter', function() {
    return function(input, degreeTypePregenerate) {
        var degreeType = {
            'assox': [],
            'bachx': ['BA', 'BS']
        };
    return degreeType[degreeTypePregenerate];
    }
});

最后,将过滤器应用于ng-repeat,并传入要过滤的变量:

<option ng-repeat="type in degreeType | orderBy:'toString()' | dropdownFilter:filter.levelPregenerate">{{type}}</option>

Working codependency: codepen