Disabling nesting filter in AngularJS

1.5k Views Asked by At

There is the following code:

tr ng-repeat="order in orders | filter: { restaurant: { id: currentRestaurant.id } } | orderBy:'-id'"

This code works good and filter orders by restaurant.id correctly. But I need to disable this filter in some case in order to show all orders. My controller code:

  $scope.setCurrentRestaurant = (restaurant) ->
    $scope.currentRestaurant = restaurant

I don't know how I can disable filtering programmatically or using filter directive. Thanks in advance.

2

There are 2 best solutions below

0
On

I think that Angular doesn't contain native features for that.

But you can create custom solution for this case.

For example, you can broadcast event, when you want to disable filter. This event can be broadcasted from anywhere (service, directive, controller). For simplicity, here I've broadcasted it from controller.

Also I've created filterByRestaurant in the controller.

View:

<div ng-controller="MyCtrl">
    <div ng-repeat="order in orders | filter:filterByRestaurant">
        {{order.name}}
    </div>
    <button ng-if="enableFilter" ng-click="disableOrEnableFilter()">Disable filter</button>
    <button ng-if="!enableFilter" ng-click="disableOrEnableFilter()">Enable filter</button>
</div>

Controller:

function MyCtrl($scope, $rootScope) {
    $scope.enableFilter = true;
    $scope.currentRestaurant = {id: 2, name: "Rest2"};

    $scope.orders = [
        {id:1, restId: 1, name: "order from Rest1"},
        {id:2, restId: 2, name: "order from Rest2"},
        {id:3, restId: 3, name: "order from Rest3"}
    ];

    $scope.filterByRestaurant = function(order) {
        return $scope.currentRestaurant.id == order.restId || !$scope.enableFilter;
    };

    $scope.$on('filter:disable', function() {
        $scope.enableFilter = !$scope.enableFilter;
    });

    $scope.disableOrEnableFilter = function(){
        $rootScope.$broadcast("filter:disable");
    };
}

This is working JSFiddle with example.

Hope it will help.

0
On

If the filter parameter is undefined then it does not filter. If the filter parameter is the filtering expression, then it filters based on that.

So, you could introduce a filter expression like so:

"filter: (enableFilter || undefined) && {restaurant:{id:currentRestaurant.id}}"

plunker