Reputation: 487
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>
Upvotes: 0
Views: 737
Reputation: 6652
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>
https://jsfiddle.net/jnokyfx9/2/
Upvotes: 2
Reputation: 32
As your array is stored in key: value manner. This is easy to sort. You need not require to write any further method or function. Just put a pipeline called filter in Angular terms in your HTML as below.
<div class="weird-reindeers" ng-repeat="Deer in Reindeers | orderBy: 'type'">{{Deer}}</div>
Upvotes: 0
Reputation: 26279
The easiest solution is to just use the default alphabetical ordering.
So since bear starts with a b, it's enough to just write:
<div class="weird-reindeers" ng-repeat="Deer in Reindeers | orderBy: 'type'">{{Deer}}</div>
See: https://jsfiddle.net/nfje5qo2/6/
Upvotes: 0