根据另一个 select angular 筛选 select 并保留第一行

Filter select based on another select angular and keep first row

我正在尝试使用 null 选项构建双 select。

一个 select 根据第一个 select 选择的选项过滤。 我遇到的问题是即使在过滤后我也想保留第一行 'null'。

我根据看到的null选项的解决方案做了一个plunker。 这是 plunker:demo

我正在尝试 select 一个国家和城市,将 'null' 选项(任何城市)保留为 select 可用选项。实现此目标的最佳方法是什么?

(我的原始问题由双重过滤组成--> select过滤国家/地区的城市)

Html:

<body ng-controller="DemoCtrl">
<h3>Countries</h3>
  <p>Selected: {{country.selected || (country.selected === null ? 'null' : '')}}</p>
  <ui-select ng-model="country.selected" theme="bootstrap" ng-disabled="disabled" style="width: 300px;">
    <ui-select-match placeholder="Select or search a country in the list...">{{$select.selected.name}}</ui-select-match>
    <ui-select-choices repeat="country in countries | filter: $select.search" null-option="anyCountry">
      <span ng-bind-html="country.name | highlight: $select.search"></span>
      <small ng-bind-html="country.code | highlight: $select.search"></small>
    </ui-select-choices>
  </ui-select>

  <h3>Cities</h3>
  <p>The loose-null option treats undefined the same as null.</p>
  <p>Selected: {{country2.selected || (country2.selected === null ? 'null' : '')}}</p>
  <ui-select ng-model="country2.selected" theme="bootstrap" ng-disabled="disabled" style="width: 300px;">
    <ui-select-match placeholder="Select or search a city in the list...">{{$select.selected.name}}</ui-select-match>
    <ui-select-choices repeat="city in cities | filter: {country: country.selected.code}" null-option="anyCity" loose-null>
      <span ng-bind-html="city.name | highlight: $select.search"></span>
      <small ng-bind-html="city.code | highlight: $select.search"></small>
    </ui-select-choices>
  </ui-select>
</body>
</html>

问题是 cities 上有一个过滤器试图将每个城市的国家/地区与所选国家/地区相匹配,目前 'Any city' 选项不符合该条件。

一种方法是保持过滤器不变,但确保 'Any city' 选项始终符合过滤条件。您可以通过在现有 anyCity 对象上设置 country 属性 并用所有可能的城市填充它来实现此目的。

$scope.anyCity = {name: 'Any city', country:['GB', 'US', 'UM']};

另一种方法是将过滤器更改为始终允许 'Any city' 选项。

查看:

<ui-select-choices repeat="city in cities | filter: countryFilter" null-option="anyCity" loose-null>

控制器:

$scope.countryFilter = function(city){
  return city === $scope.anyCity
  || city.country === $scope.country.selected.code;
}

哪个更好?第一种方法在这个例子中很简单,但对于一长串国家来说就不太理想了。如果您的数据可以更改,则需要动态填充它。我更喜欢第二个,因为它更明确地说明了预期的功能。