Reputation: 852
I have a select dropdown with different sorting options, one of which is rarity. The rarities are common, uncommon, rare, ..., etc however (as expected) when sort by rarity is selected, the items are ordered by rarity in alphabetical order. Is there a way to specify a different way of ordering the rarities - that is, in a fixed order?
The rarities are common, uncommon, rare, mythical, legendary, ancient, immortal, arcana (from Dota2 in case you're wondering.)
So for example, instead of alphabetical order of rarities which is the default, I would like it in the order displayed above.
Below is what I've tried:
<select class="form-control" id="select-sorting" ng-model="orderProp">
<option value="">No Sorting</option>
<option value="used_by_heroes">Hero</option>
<option value="class">Type</option>
<option value="rarityOrder">Rarity</option>
</select>
...
<div ng-repeat="item in items" ... orderBy:orderProp>
...
</div>
And within the directive:
var mapping = {
'common': 0,
'uncommon': 1,
'rare': 2,
...
};
scope.rarityOrder = function(item) {
return mapping[item.item_rarity];
};
Upvotes: 0
Views: 221
Reputation: 786
<script>
angular.module('orderByExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.friends =
[{name:'John', phone:'555-1212', age:10},
{name:'Mary', phone:'555-9876', age:19},
{name:'Mike', phone:'555-4321', age:21},
{name:'Adam', phone:'555-5678', age:35},
{name:'Julie', phone:'555-8765', age:29}];
$scope.predicate = '-age';
}]);
</script>
<div ng-controller="ExampleController">
<pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre>
<hr/>
[ <a href="" ng-click="predicate=''">unsorted</a> ]
<table class="friend">
<tr>
<th><a href="" ng-click="predicate = 'name'; reverse=false">Name</a>
(<a href="" ng-click="predicate = '-name'; reverse=false">^</a>)</th>
<th><a href="" ng-click="predicate = 'phone'; reverse=!reverse">Phone Number</a></th>
<th><a href="" ng-click="predicate = 'age'; reverse=!reverse">Age</a></th>
</tr>
<tr ng-repeat="friend in friends | orderBy:predicate:reverse">
<td>{{friend.name}}</td>
<td>{{friend.phone}}</td>
<td>{{friend.age}}</td>
</tr>
</table>
</div>
May be the above code could help you!!
You can modify your to include 'predicate' and that should work I guess.
Upvotes: -1
Reputation: 26828
You can provide a mapping function.
In your HTML:
"items | orderBy: rarityOrder"
In your controller:
var mapping = {
'rare': 0,
'uncommon': 1
...
};
$scope.rarityOrder = function(rarity) {
return mapping[rarity];
}
Upvotes: 2