How do you sort the AngularFire collection?

  $scope.items = [];
  var ref = new Firebase("https://****.firebaseio.com/");
  var query = ref.limit(5);

  angularFire(query, $scope, "items");

<div ng-repeat="item in items" >
<span>{{item.title}}</span>
</div>

How would you sort them by name? I saw a couple of similar questions, but the solutions do not seem to work, at least for this situation.

+4
source share
1 answer

If it $scope.itemswas an array of objects (as implied $scope.items = []), you could use an angular orderBy filter :

<!-- This example will NOT work with Firebase -->
<div ng-repeat="item in items | orderBy:'title'">
  <span>{{item.title}}</span>
</div>

, items , , , ( ) "" , . javascript , - :

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;
  }
});

item:

<div ng-repeat="item in items | orderObjectBy:'title'">
  <span>{{item.title}}</span>
</div>

fiddle, . @bennlich , , orderBy, .

, , " " Firebase .

+4

All Articles