how to order by numeric and character

55 Views Asked by At

PLUNKER

I have a ng-repeat, and in the drop down there are the following values.

Up to 6 months
From 13 to 24 months
Higher than 24 months
From 6 to 12 months

and I need to sort the values like the following

//following is the expected output
// Up to 6 months
//From 6 to 12 months
//From 13 to 24 months
//Higher than 24 months




$scope.items = [{name: 'Up to 6 months', id: 30 },{ name: 'From 13 to 24 months', id: 27 },{ name: 'Higher than 24 months', id: 50 },{ name: 'From 6 to 12 months', id: 50 }];
2

There are 2 best solutions below

6
I. Ahmed On

Your name field is not formatted text you cannot do order by on name, add one field like follows which will fill the field value with sorted criteria. An example sort function is given here:

$scope.items.sort(
function(a,b) {
// Change the logic based on your criteria
return (/*Your criteria*/) ? 1 : 0);
} 
);

Your data then will be like follows:

$scope.items = [{name: 'Up to 6 months',sort:0, id: 30 },{ name: 'From 13 to 24 months',sort:1, id: 27 },{ name: 'Higher than 24 months',sort:3, id: 50 },{ name: 'From 6 to 12 months', sort:4, id: 50 }];

Use the following:

<div ng-repeat="item in items | orderBy:['sort','id']">{{item.name}}-{{item.id}}</div>
0
LINTO TOM On

Your Items will be load like this,

 $scope.selectedItem = { name: 'two', id: 27 };
 $scope.items = [{name: 'Up to 6 months',sort:1, id: 30 },{ name: 'From 13 to 24 months',sort:3, id: 27 },{ name: 'Higher than 24 months',sort:4, id: 50 },{ name: 'From 6 to 12 months', sort:2, id: 50 }];

ng-repeat

<select ng-model="selectedItem">
   <option ng-repeat="item in items  | orderBy:['sort']" value={{item.id}}>
    {{item.name}}
   </option>
</select>