Angular checkbox filtering data list

后端 未结 2 1803
太阳男子
太阳男子 2021-01-28 02:10

Seen a few options for filtering data via checkboxes but it all seems fairly overly complicated for something I\'d expect Angular to do easily.

Take a nose at http://pln

2条回答
  •  北海茫月
    2021-01-28 02:37

    Just for the fun of it, I implemented a solution that has a much simpler API (wish of Leads in comments). Here it goes:

    Add the cbFilter dependency to the controller, remove all the checkbox-related code and replace it as follows; this is the new API (it can't get any simpler :)

    app.controller('resultsData', function($scope, $http, cbFilter){
        ...
        $scope.checkbox = cbFilter($scope, "provider.providerId");
        ...
    }
    

    Rreplace the filter in the list (notice searchByCheckbox is replaced by checkbox):

  • And, finally, add the service:

    app.factory("cbFilter", ["$parse", function($parse) {
        return function($scope, matchExpression) {
            var showAll = true,
                getter = $parse(matchExpression),
                filter = function(data) {
                    if( showAll ) return true;
                    return filter[getter(data)] === true;
                },
                unwatch = $scope.$watch(
                    function() {
                        var x, ret = {};
                        for( x in filter ) {
                            if( !filter.hasOwnProperty(x) ) continue;
                            ret[x] = filter[x];
                        }
                        return ret;
                    },
                    function() {
                        showAll = true;
                        angular.forEach(filter, function(val) {
                            if( val === true ) showAll = false;
                        });
                    },
                    true
                );
    
            $scope.$on("$destroy", unwatch);
    
            return filter;
        };
    }]);
    

    The implementation is much more complex than before, and probably slower. However the API is much simpler (one-liner).

提交回复
热议问题