AngularFire以相反的顺序添加

时间:2014-01-05 12:30:31

标签: angularjs firebase angularfire

我需要以相反的顺序向Firebase添加对象。或者在进行数据绑定时反转数据。或者按创建时间对对象进行排序。

var ref = new Firebase("https://[url].firebaseio.com/");
$scope.messages = $firebase(ref);

$scope.addMessage = function(e) {
    $scope.messages.$add({title: $scope.title, body: $scope.msg, time: $scope.getDate() });
}

<div class="well span3 pull-left note" ng-repeat="(key, msg) in messages">

    <button type='button' class='close' ng-click="messages.$remove(key)">×</button>
    <b>{{msg.time| date: 'medium'}}</b>
    <span>{{msg.title}}</span>
    <span>{{msg.body}}</span>
    <button ng-click="changeMessage(key)" class="btn btn-mini pull-right"><i class="icon-pencil"></i></button>      
</div>  

我尝试将OrderBy属性用于ng-repeat,但这并不容易,因为在消息中存储了对象。

1 个答案:

答案 0 :(得分:13)

查看chat example in angularFire-seed。它使用custom reverse filter

反向过滤器如下所示:

app.filter('reverse', function() {
      function toArray(list) {
         var k, out = [];
         if( list ) {
            if( angular.isArray(list) ) {
               out = list;
            }
            else if( typeof(list) === 'object' ) {
               for (k in list) {
                  if (list.hasOwnProperty(k)) { out.push(list[k]); }
               }
            }
         }
         return out;
      }
      return function(items) {
         return toArray(items).slice().reverse();
      };
   });

用法如下:

<ul id="messages" ng-show="messages">
    <li ng-repeat="message in messages | reverse">{{message.text}}</li>
</ul>