gpt4 book ai didi

javascript - 根据另一个选择 Angular 过滤选择并保留第一行

转载 作者:行者123 更新时间:2023-11-29 15:32:26 25 4
gpt4 key购买 nike

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

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

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

我正在尝试选择一个国家和城市,将“空”选项 (anyCity) 保留为 optional 。实现这一目标的最佳方法是什么?

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

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>

Controller :

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

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

关于javascript - 根据另一个选择 Angular 过滤选择并保留第一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33477757/

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