furier
furier

Reputation: 1977

AngularJS ui-grid data value and display value

I am looking at using the AngularUI team's new table / grid implementation ui-grid. It looks really great, promising and easy to use.

Tho I have a question / problem I can't find the answer to in the documentation.

I want a column to sort on a different value then the one displayed, how can I achieve that?

I have a rank property ranging from 1 to 10 which I want to sort on but I have a rank_name property I want to be displayed.

The rank property would be the data value and the rank_name would be the display value for the column.

var members = [
    {
        name: 'Member 1',
        rank: 1,
        rank_name: 'Grand Admiral'
    },
    {
        name: 'Member 2',
        rank: 2,
        rank_name: 'Aspirant'
    }
]

Take the following list of members as an example, the rank property should not be its own column but be hidden, the rank_name should be visible as its own column.

But if you try and sort members from highest rank to lowest rank it would sort it alphabetically and not by the rank number which is the real rank indicator. Thus placing the Aspirant at the top and not the Grand Admiral.

$scope.gridOptions = {
    enableSorting: true,
    enableFiltering: true,
    columnDefs: [
        {field: 'name'},
        {field: 'coords'},
        {field: 'rank_name', name: 'rank'},
        {field: 'score'},
        {field: 'strength'},
        {field: 'level'},
        {field: 'outposts'},
        {field: 'public_note'}
    ],
    data: members
};

Here is the grid options i currently use, but would like to add a sort value for the column definition for rank.

{display_field: 'rank_name', name: 'rank', value_field: 'rank'},

Upvotes: 0

Views: 5483

Answers (2)

hjl
hjl

Reputation: 2802

write rankToString filter in your angular module

module.filter('rankToString', function () {
    return function(input) {
        switch(input) {
        case 1:
            return 'Grand Admiral';
        case 2:
            return 'Aspirant';
        }
    };
}

columnDef for rank, you still sort on rank number but show the string value in viewport. so you can dump rank_name filed.

{
    field: 'rank',
    sort: {
        direction: uiGridConstants.ASC
    },
    cellFilter: 'rankToString'
}

Upvotes: 3

hjl
hjl

Reputation: 2802

add below to rank_name columnDef

sort: {
    direction: uiGridConstants.ASC
},
sortingAlgorithm: function(a, b) {
    var rank = {
        'Grand Admiral': 1,
        'Aspirant': 2
    };

    if (rank[a] > rank[b]) {
        return 1;
    }

    if (rank[a] < rank[b]) {
        return -1;
    }

    return 0;
}

Upvotes: 1

Related Questions