3

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?

1 Answer 1

1

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;
}
Sign up to request clarification or add additional context in comments.

11 Comments

You've got crazy rep, @charlietfl. Thanks! Will take a look!
For some unknown reason I cannot fathom, this isn't working for me either, :(
Ideally, however, I would prefer to keep my custom filters separate, since some lists will not be using all of the filters.
Fair enough..can also set a default in filter if that helps
using getSortFunction filter and $filter
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.