繁体   English   中英

根据另一个选择角度过滤选择并保留第一行

[英]Filter select based on another select angular and keep first row

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

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

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

我试图选择一个国家和城市,保持'null'选项(anyCity)作为可选择的选项。 实现这一目标的最佳方法是什么?

(我原来的问题包括双重过滤 - >选择一个城市也过滤国家)

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中有一个过滤器,试图将每个城市的国家与所选国家进行匹配,目前“任何城市”选项都不符合该标准。

一种方法是按原样保留过滤器,但确保“任何城市”选项始终满足过滤条件。 您可以通过在现有anyCity对象上设置country属性并使用所有可能的城市填充它来实现此目的。

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

另一种方法是将过滤器更改为始终允许“任何城市”选项。

视图:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM