When dealing with $scope.items
as an array of objects (as indicated by $scope.items = []
), you have the option to utilize the angular orderBy
filter:
<!-- This example will NOT work with Firebase -->
<div ng-repeat="item in items | orderBy:'title'">
<span>{{item.title}}</span>
</div>
However, it's worth mentioning that setting items
as an array can be misleading, since you are actually storing and accessing your "items" as a list of key-value pairs, not an array. Sorting objects in javascript is generally more complex, but one approach to achieve this is by using a custom filter:
app.filter('orderObjectBy', function(){
return function(input, attribute) {
if (!angular.isObject(input)) return input;
var array = [];
for(var objectKey in input) {
array.push(input[objectKey]);
}
function compare(a,b) {
if (a[attribute] < b[attribute])
return -1;
if (a[attribute] > b[attribute])
return 1;
return 0;
}
array.sort(compare);
return array;
}
});
With this custom filter, you can now order by any property of your item
:
<div ng-repeat="item in items | orderObjectBy:'title'">
<span>{{item.title}}</span>
</div>
Here's a fiddle for demonstration purposes. Additionally, your custom filter could potentially simplify by stopping at the array conversion, allowing you to use the standard orderBy filter as suggested here.
Lastly, it's important to note that you also have the option to sort "server-side" with Firebase priorities.