AngularJS - 过滤多选

时间:2015-11-27 18:51:04

标签: javascript angularjs ngtable

我使用$ filter来过滤我的数组。

var filteredData = params.filter() ?
    $filter('filter')($scope.myNgTable.data, params.filter()):
    $scope.myNgTable.data;

我创建了一个多选过滤器,用于过滤,但它返回一个数组: col:[“a”,“b”],对于我看到的内容,它不适用于$ filter。

我希望当过滤器为col:[“a”,“b”]时,它会显示col包含“a”或col包含“b”的所有行。 (如果只有一种方法可以等于罚款:col ==“a”或col ==“b”)

这可能吗?

答案:

.filter("in_Array", function ($filter){
    return function(data, filter){
        var out = [];
        $.each(filter, function(key,val) {
            var obj = {};
            for(var i=0;i<val.length;i++) {
                obj[key] = val[i];
                var tmp = $filter('filter')(data, obj);
                out = $.unique($.merge(out, tmp));
            }
        });
        return out;
    };
});

1 个答案:

答案 0 :(得分:0)

看这个例子。单击复选框

时使用多重过滤器

http://jsfiddle.net/rzgWr/123/

<强> HTML:

 <div ng-controller="MyCtrl">
        <h4>Pick a brand to see the models</h4>
        <div ng-init="group = (cars | groupBy:'make')" style="width:100%">
            <div ng-repeat="m in group"   style="width:100px; float:left;">
                <b><input type="checkbox" ng-model="useMakes[$index]"/>{{m}}</b>
            </div>
        </div>
        <div style="clear:both;"></div>
        <div>
            <ul>
                <li  ng-repeat="car in cars | filter:filterMakes()"><p><b>{{car.make}} - {{car.model}}</b></p></li>
            </ul>    
        </div>
    </div>

<强> JS:

var myApp = angular.module('myApp',[]);

function MyCtrl($scope, filterFilter) {
    $scope.useMakes = [];

    $scope.filterMakes = function () {
        return function (p) {
            for (var i in $scope.useMakes) {
                if (p.make == $scope.group[i] && $scope.useMakes[i]) {
                    return true;
                }
            }
        };
    };

    $scope.cars = [
        {model: '316', make: 'Bmw'},
        {model: '520', make: 'Bmw'},
        {model: 'Fiesta', make: 'Ford'},
        {model: 'Focus', make: 'Ford'},
        {model: 'Clio', make: 'Renault'},
        {model: 'Toledo', make: 'Seat'},
        {model: 'Leon', make: 'Seat'},
        {model: 'Insignia', make: 'Opel'},
        {model: 'Astra', make: 'Opel'},
        {model: 'Corsa', make: 'Opel'}
    ];    
}


var uniqueItems = function (data, key) {
    var result = new Array();
    for (var i = 0; i < data.length; i++) {
        var value = data[i][key];

        if (result.indexOf(value) == -1) {
            result.push(value);
        }

    }
    return result;
};

myApp.filter('groupBy',
function () {
    return function (collection, key) {
        if (collection === null) return;
        return uniqueItems(collection, key);
    };
});