2015-11-02 86 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

相關問題