AngularJS:从 Firebase 获取分页记录 [英] AngularJS : Fetch records for pagination from Firebase

查看:26
本文介绍了AngularJS:从 Firebase 获取分页记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 AngularJS 和 Firebase 作为后端来实现分页.我正在使用以下代码从 firebase url 获取数据:

I'm trying to implement pagination using AngularJS with Firebase as back end. I'm using the below code to fetch data from firebase url:

var firebaseObj = new Firebase("<firebaseUrl>.com/Details/");

var sync = $firebase(firebaseObj.startAt($scope.username).endAt($scope.username).limitToFirst(5));

$scope.articles = sync.$asArray();

上面的查询给出了前 5 条记录,它们以特定的 username 开始和结束.现在如何从索引 6 到 10 获取下一组数据.任何帮助将不胜感激...

The above query gives me the first 5 records which start and end with the particular username. Now how to get the next set of data from index 6 to 10. Any help would be appreciated ...

推荐答案

Firebase 中没有偏移功能,当您开始了解实时、协作方面时,这很有意义(偏移在流体数据集).

There is no offset function in Firebase, which makes some sense when you begin to grok the real-time, collaborative aspects (an offset has no real meaning in a fluid data set).

您的具体问题的答案实际上和听起来一样简单.该算法是一种基本的游标策略,看起来像这样:

The answer to your specific question is actually as simple as it sounds. The algorithm is a rudimentary cursor strategy, and would look something like this:

  • 从当前数据集中找到最后一个键
  • 使用 startAt 和 limit 来抓取下一组(页数加一)
  • 丢弃第一个键
  • 将数据应用到 $scope

看起来像下面这样:

function getLastKey(obj) {
    return Object.keys(obj).pop();
}

function nextPage() {
   var lastKey = Object.keys($scope.articles);
   // stop listening to the old data
   $scope.articles.$destroy();
   var ref = firebaseObj.orderByKey()
      .startAt(lastKey)
      // 5 + 1 to account for the lastKey being in the results
      .limitToFirst(6);
   // sync to the new results
   $scope.articles = $firebase(ref).$asArray();
}

在实践中,要在 Angular 中优雅地进行分页,还有很多工作要做.

In practice, there's a lot more work to be done to make pagination work elegantly in Angular.

其中最明显的是我们需要有一些跳过第一条记录的方法.大概我们知道页码,因此可以使用自定义过滤器函数从 ng-repeat 中过滤掉第一项.

The most obvious of which is that we need to have some means of skipping the first record. Presumably we'd know the page number and could therefore filter out the first item from ng-repeat with a custom filter function.

另外,看看这个 jsfiddle 展示了一个简单的分页类.

这篇关于AngularJS:从 Firebase 获取分页记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆