Angular orderBy number sorting as text in ng-repeat

前端 未结 7 1458
天命终不由人
天命终不由人 2020-11-29 08:10

I have this data:

[{\"id\":\"42\",\"firstname\":\"Sarah\",\"lastname\":\"Dilby\",\"age\":\"40\",\"cars\":\"Yaris\"},
{\"firstname\":\"Jason\",\"lastname\":\"         


        
7条回答
  •  生来不讨喜
    2020-11-29 08:48

    It is best to update your repeating collection whenever a sort function is called. Here I am using Lodash - orderBy just to order the collection based on a sorter function. Lets say the sort is called on click of table column head.

    Example:

    Collection object:

    ctrl.people = [{"id":"42","firstname":"Sarah","lastname":"Dilby","age":"40","cars":"Yaris","salary": 700}, {"firstname":"Jason","lastname":"Diry","age":"5","id":"5","cars":"Lexia","salary": 500},{"id":"6","firstname":"Bilson","lastname":"Berby","age":"1","cars":"Tipo","salary": 400}];
    

    User clicks column head to sort by age:

    Age
    

    Method called:

    ctrl.sortColumn('age'); // where age is column containing numbers only
    

    Method implementation:

    ctrl.sortedCol = 'firstname';    //Default sort column
    
    ctrl.sortColumn = (column) => {
        ctrl.sortedCol = column; //age
        let order = 'asc'; //you can decide the order based on your own logic
        ctrl.people = _.orderBy(ctrl.people, [ctrl.sorter], [order]);   //update the collection
    };
    
    ctrl.sortColumn(ctrl.sortedCol); //called on initial rendering
    

    Sorter function: Returns the sorted collection based on column type

    ctrl.sorter = (item) => {
        const columnType = ctrl.getColumnType();
        if(item[ctrl.sortedCol] && columnType === 'string'){
            return item[ctrl.sortedCol].toLowerCase();
        } else if(item[ctrl.sortedCol] && columnType === 'number'){
            return parseInt(item[ctrl.sortedCol]);
        } else{
            return item[ctrl.sortedCol];
        }    
    };
    

    Decide column type: Can be string, number or even date

    ctrl.getColumnType = () => {
        if(ctrl.sortedCol === 'firstname' || ctrl.sortedCol === 'lastname' || ctrl.sortedCol === 'cars'){
            return 'string';
        } else if(ctrl.sortedCol === 'salary' || ctrl.sortedCol === 'age'){
            return 'number';
        }
    };
    

提交回复
热议问题