我有两个数组,国家/地区和 selectedCountries 。
用户可以将国家从国家/地区添加到 selectedCountries 。
现在,我只想显示用户没有选择的国家(selectedCountries中的用户) - 但是我无法想象如何实现这一目标。
这是HTML:
<div ng-controller="MyCtrl">
<select
ng-model="selectedCountry"
ng-options="country.name for country in countries"></select>
<button ng-click="addCountry(selectedCountry)">Add country</button>
<table>
<tr ng-repeat="country in selectedCountries">
<td>{{ country.name }}</td>
</tr>
</table>
</div>
目前的Javascript:
function MyCtrl($scope) {
$scope.countries = [
{ id: 1, name: 'Denmark' },
{ id: 2, name: 'Sweden' },
{ id: 3, name: 'Norway' }
];
$scope.selectedCountries = [];
$scope.addCountry = function(country) {
$scope.selectedCountries.push(country);
}
}
如何过滤显示的国家/地区?
这是一个有效的JSFiddle
答案 0 :(得分:2)
为它创建一个过滤器。你的HTML:
ng-options="country.name for country in countries |notin:selectedCountries"
你的过滤器:
app.filter('notin',function(){
return function(items,matchset) {
return items.filter(function(item){
return matchset.indexOf(item) < 0;
});
};
});
它会自动使它们保持最新状态。更新了小提琴:http://jsfiddle.net/jxwbwjdq/1/
答案 1 :(得分:1)
控制器:
$scope.notinSelectedCountries=function(item)
{
if ($scope.selectedCountries.indexOf(item) < 0)
return true
}
查看:
ng-options="country.name for country in countries | filter :notinSelectedCountries"
它不会改变数组,只需使用过滤器
答案 2 :(得分:0)
为什么不选择$scope.countries
中选择的国家/地区:
$scope.addCountry = function(country) {
$scope.selectedCountries.push(country);
$scope.countries.splice($scope.countries.indexOf(country), 1);
}
使用过滤器的另一种有效方法是将国家/地区对象标记为已选中,并过滤掉未选中的对象:
$scope.addCountry = function (country) {
$scope.selectedCountries.push(country);
country.selected = true;
}
<select ng-model="selectedCountry"
ng-options="country.name for country in countries|filter:{selected:'!true'}">
</select>
答案 3 :(得分:0)
在js中更改此内容:
$scope.addCountry = function(country) {
$scope.selectedCountries.push(country);
$scope.notselectedcountries = [];
$scope.countries.map(function(item) {
if($scope.selectedCountries.indexOf(item) < 0)
$scope.notselectedcountries.push(item);
})
}
这在你的html中:
<table ng-if="notselectedcountries.length > 0" border="1">
答案 4 :(得分:0)
如果您想保持countries
不变,可以将select绑定到函数而不是从selectedCountries
过滤掉countries
的列表:
在你的控制器中添加
$scope.unselectedCountries = function() {
return $scope.countries.filter(function(c) {
return $scope.selectedCountries.indexOf(c) == -1;
});
};
然后
<select
ng-init="selectedCountry = countries[0]"
ng-model="selectedCountry"
ng-options="country.name for country in unselectedCountries()">
</select>