简体   繁体   中英

AngularJS Filter Best Practice

I have a filter I need to use two times (two pages/controllers), filtering on an object category. I can get this to work using this in each controller:

     $scope.$on('category', function (event, arg) {
                $scope.catSort = arg;
            });    

     $scope.filterCat = function (item) {
                return !$scope.catSort ?
                    item : (item.category == $scope.catSort);
            };

The html i am filtering on:

 <li dnd-draggable="item" ng-repeat="item in items| filter: filterCat">
        </li>

I set the $scope.catSort which is what to filter on in a list of buttons the user can click:

<button class="btn btn-default" ng-click="$emit('category', 'all')">Show All</button>
<button class="btn btn-default" ng-click="$emit('category', 'Common')">Common</button>

The problem is, i have another html page with a different subset of categories that I need to filter on. Instead of just copying and pasting the $scope.filterCat function to filter again, I want to create a separate filter to inject into each controller (Thats best practice right?).

So what i have started is this for a separate filter:

angular.module("category-filter", [])
    .filter('filterCat', function () {
        return function (category, item) {
            return !category ?
                product : (item.category == $scope.catSort);
        }
    });

You can see i'm trying to get that category option as well. How do i reach into the scope and get the category? Should i use a service and on one of the button clicks set the category to filter on?

I'm still learning filters and what want to make sure its reusable and following best practices

将对象传递给过滤器表达式: filter:{category: '...', compareTo: '...'}并在filter函数中检查它。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM