I was wondering if it is possible to order by a list based on a string, for e.g.
I want all the Bear
's to come first in my ng-repeat based on item.type
.
Data:
$scope.Reindeers = [{
"name": "Vixen",
"type": "Bear"
},
{
"name": "Prancer",
"type": "Dog"
},
{
"name": "Dancer",
"type": "Cat"
},
{
"name": "Rudolph",
"type": "Bear"
}]
AngularJS e.g.
<div class="weird-reindeers" ng-repeat="Deer in Reindeers | orderBy: 'type == Bear'"></div>
The argument to orderBy
can be a function: https://docs.angularjs.org/api/ng/filter/orderBy#orderBy-arguments
Write a function that returns a value used for sorting. The highest priority should return the lowest value:
$scope.orderByBears = function(item) {
switch(item.type) {
case "Bear":
return -10;
/*case "Dog":
return -5;*/
default:
return 0;
}
}
Then use this as your orderBy
function:
<div class="weird-reindeers" ng-repeat="Deer in Reindeers | orderBy: orderByBears"></div>