Skip to content Skip to sidebar Skip to footer

Dynamic Orderby In Angularjs

I have an array of objects I want to order dynamically, based on a value from a drop down menu. This is what I have so far in my list: ng-repeat='item in filteredItems = (items | f

Solution 1:

Update orderBy:myCalculatedValueFunction to something like orderBy:dynamicOrderFunction:

ERRONEOUS

$scope.dynamicOrderFunction = function() {
    if (orderByString) {
        return'-creationDate';
    }
    else {
        return myCalculatedValueFunction;
    }
}

orderBy also has a 3rd property that accepts a boolean and will reverse orderBy when true. (orderBy:dynamicOrderFunction:reverseOrder where $scope.reverseOrder = true; // or false)


edit

You will actually run into issues trying to switch orderBy between a string a function this way. Checkout out this jsfiddle for a working dynamic order function.

$scope.dynamicOrder = function(user) {
    var order = 0;
    switch ($scope.order.field) {
        case'gender':
            order = gender_order[user.gender];
            break;
        default:
            order = user[$scope.order.field];
    }
    return order;
}

Solution 2:

So you have to create your own filter and do what ever you want in it, there's tons of example on google. Just search :

angular custom filter

Theses last days, i experience somes issues with filters creation and i found that: https://github.com/a8m/angular-filter

I've added it immediately in my dependcies, i know i will use it really soon. May be it will help you too. Don't forget to valid my answer if it helps you to resolve your problem ;)

Post a Comment for "Dynamic Orderby In Angularjs"