javascriptangularjsangularjs-orderby

AngularJS dynamic sort function with parameters


Based on Dynamic orderBy in AngularJS I try to implement a dynamic sort function with parameters. It's not working properly because the default sort is being called. How can I make it not calling the default sort by name?

I have 2 buttons to call the function and send the parameter.

<button ng-click="dynamicOrder('f9.id')" class="btn">Sort by rating</button>            
<button ng-click="dynamicOrder('name')" class="btn">Sort alphabetic</button>

My ng-repeat looks like this:

<li ng-repeat="item in cumulus.items | orderBy: dynamicOrder()"
    ng-show="cumulus.items.length > 0" class="block-grid-item">
    <p>
        <a target="_blank" href="{{ item.image }}">
            <img class="img-responsive" src="{{ item.thumb }}">
        </a>
    </p>
    <p style="overflow: hidden;">{{ item.name }}</p>                    
    <p class="text-primary"><input type="hidden" value="{{ item.f9.id }}" /> {{ item.f9.displaystring }}</p>
</li>

and my function for order

$scope.dynamicOrder = function (sortParam) {
    if (!sortParam) {            
        return 'name';
    } else {
        console.log("sortParam: ", typeof (sortParam), sortParam);
        return sortParam;
    }  
};

Solution

  • The orderBy expression can be a getter function. This function will be called with each item as argument and the return value will be used for sorting.

    $scope.getterFn = function(item) {
        if ($scope.dynamicOrder == 'f9.id') {
            return item.f9.id;
        } else if ($scope.dynamicOrder == 'name') {
            return item.name;
        } else {
            return item;
        }
    };
    

    Usage:

    <button ng-click="dynamicOrder = 'f9.id'" class="btn">Sort by rating</button>
    <button ng-click="dynamicOrder = 'name'" class="btn">Sort alphabetic</button>
    
    <li ng-repeat="item in cumulus.items | orderBy: getterFn">
    
        <!-- ... -->
    
    </li>   
    

    For more information, see