Search code examples
angular-ui-gridui-grid

ui-grid get the current column (field) name from inside a custom sorting algorithm?


Once you define custom sorting for a column like in Github and UI-Grid

How can you access the column from inside the algorithm?

var myAwesomeSortFn = function(a,b, rowA, rowB, direction){

       // "Need to access the name (field) of column being sorted here";
        var column = "No Idea"

       console.log("sorting by column " + column );

        if (a == b) return 0;
        if (a < b) return -1;
        if (a > b) return 1;


    };  

Solution

  • You could try the following...

    { field: 'lastName', displayName: 'Last Name', sortingAlgorithm: MyService.getSortingAlgorithm('lastName') },
    

    Then define in a service (or in your scope if you prefer)

    getSortingAlgorithm: function (columnName) {
        return function(a, b, rowA, rowB, direction) {
            console.log("sorting by column " + columnName);
    
            if (a == b) return 0;
            if (a < b) return -1;
            if (a > b) return 1;
        };  
    }