Dynamic orderBy in AngularJS

后端 未结 2 1693
忘了有多久
忘了有多久 2020-12-19 08:22

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 fi         


        
2条回答
  •  孤城傲影
    2020-12-19 08:57

    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;
    }
    

提交回复
热议问题