Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switching Between Angular Filters On Button Click

I have written a few different custom filters in my angular module to achieve the sorting that I want, e.g.

Angular:

var sortByValue = function() {
    return function(input) {
       /*...*/
       return some_boolean;
    }
};

var sortByCount = function() {
    return function(input) {
       /*...*/
       return some_boolean;
    }
};

In my HTML (jade), I can call the different filters as such:

.row(ng-repeat='item in array | sortByValue')

OR

.row(ng-repeat='item in array | sortByOrder')

I wish now to add a button that toggles between the two different sorting options.


I tried to do this by defining a new overall filter function that makes use of a $scope variable to keep track of the toggle (see below), but it isn't working.

Angular:

var myController = function($scope) {
    // function called on ng-init
    $scope.initialize = function() {
        $scope.byValue = true;
    }
};

var sortFunction = function() {
    if($scope.byValue) {
        return sortByValue();
    } else {
        return sortByCount();
    }
}

I have also tried passing in the $scope variable to the filter in the HTML itself, e.g. sortFunction:byValue but it also doesn't work.

Can anyone help? Thank you!


Demo plunker @ plnkr.co/edit/altzOow7aIQhqKTN93Oe?p=preview?

like image 725
Tacocat Avatar asked Mar 18 '26 08:03

Tacocat


1 Answers

Can use one custom filter function and an argument

app.filter('mySorter', function(){
    return function(items, sortType){
        // sort logic
        if(!items) return;
        return items.sort(function(a, b){
            if(sortType=== 'order'){
               // order matching
             }else{
               // value matching
             }
        });
    }

});

HTML

.row(ng-repeat='item in array | mySorter: sortType')

<button ng-click="toggleSort('order')">

Then in controller switch around variable sortType

$scope.sortType = 'order' // or 'value'

$scope.toggleSort = function(type){
    $scope.sortType = type;
}
like image 91
charlietfl Avatar answered Mar 19 '26 22:03

charlietfl