存在于另一个数组中的过滤器选项

Filter options which exists in another array

本文关键字:过滤器 选项 数组 另一个 存在      更新时间:2023-09-26

我有两个数组,国家选定国家

用户可以将国家/地区从国家/地区添加到所选国家/地区

现在,我只想显示用户尚未选择的国家/地区(所选国家/地区中的国家/地区) - 但是我不知道如何实现这一点。

这是 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

为它创建一个过滤器。您的网页:

        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/

控制器:

   $scope.notinSelectedCountries=function(item)
                        {
                            if ($scope.selectedCountries.indexOf(item) < 0)
                            return true
                        }

视图:

ng-options="country.name for country in countries | filter :notinSelectedCountries"

它不会改变数组,只需使用过滤器

在你的 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">
如果要

保持countries完整,可以将选择绑定到函数,而不是从countries中过滤掉selectedCountries的列表:

在控制器中添加

$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>

更新的小提琴

为什么不在选择国家/地区时将其从$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>

http://codepen.io/anon/pen/YPqWNo