【问题标题】:Filter select based on another select angular and keep first row根据另一个选择角度过滤选择并保留第一行
【发布时间】:2015-11-03 03:51:32
【问题描述】:

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

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

我根据我看到的 null 选项的解决方案制作了一个 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>

【问题讨论】:

    标签: javascript angularjs ui-select


    【解决方案1】:

    问题是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;
    }
    

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

    【讨论】:

    • 谢谢,我实际上已经尝试过这样的事情,似乎可行,只是我使用了逗号分隔的值而不是数组......它应该可行吗? (就像你的第一个例子)
    • 是的,带有逗号分隔值的字符串会起作用,因为filter: 会匹配(docs) 的子字符串。如前所述,为了清晰起见,我更喜欢范围函数方法,以防数据发生变化,但您的方法也应该可靠地工作。
    猜你喜欢
    • 2019-03-13
    • 2017-12-26
    • 1970-01-01
    • 2021-12-04
    • 1970-01-01
    • 2020-06-14
    • 1970-01-01
    • 2016-04-07
    • 1970-01-01
    相关资源
    最近更新 更多