How to chain AngularJS filters in controller

前端 未结 3 1082
南方客
南方客 2020-12-30 00:32

I have few filters in view

  

In my proje

3条回答
  •  囚心锁ツ
    2020-12-30 01:22

    In addition to explicitly applying filters to the result of the previous one you could also build an object that will chain multiple filters together.

    Controller

    angular.module('Demo', []);
    
    angular.module('Demo')
        .controller('DemoCtrl', function($scope, $filter) {
    
            $scope.order = 'calories';
            $scope.filteredFruits = $scope.fruits = [{ name: 'Apple', calories: 80 }, { name: 'Grapes', calories: 100 }, { name: 'Lemon', calories: 25 }, { name: 'Lime', calories: 20 }, { name: 'Peach', calories: 85 }, { name: 'Orange',    calories: 75 }, { name: 'Strawberry', calories: 65 }];
    
            $scope.filterFruits = function(){
                var chain = new filterChain($scope.fruits);
                $scope.filteredFruits = chain
                    .applyFilter('filter', [{ name: $scope.filter }])
                    .applyFilter('orderBy', [ $scope.order ])
                    .value;
            };
    
            function filterChain(value) {
                this.value = value;
            }
    
            filterChain.prototype.applyFilter = function(filterName, args) {
                args.unshift(this.value);
                this.value = $filter(filterName).apply(undefined, args)
                return this;
            };
        });
    

    View

    
    
      
        
        
        
      
      
    
    
    Name: {{fruit.name}} Calories: {{fruit.calories}}

提交回复
热议问题