2015-11-02 87 views
3

我正尝试使用null选项构建双选择。基于另一个选择角度过滤器选择并保持第一行

根据第一个选择选择选项筛选一个选择。 我有的问题是我想保留第一个'空'行,即使过滤器。

我做了一个基于我看到的null选项的解决方案。 这里的掠夺者: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> 

回答

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

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

+1

谢谢,我已经尝试过类似的东西,似乎工作,只有我用逗号分隔值而不是数组...它假设它工作吗? (就像你的第一个例子) –

+1

是的,逗号分隔值的字符串可以工作,因为'filter:'的子字符串匹配[(docs)](https://docs.angularjs.org/api/ng/filter/filter)。如前所述,为了清晰起见,我更喜欢范围函数方法,以防数据发生变化,但您的工作也应该可靠。 – sheilak

相关问题