AngularJS : Fetch records for pagination from Firebase

荒凉一梦 提交于 2019-12-17 17:08:36

问题


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

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 ...


回答1:


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:

  • find the last key from the current data set
  • use startAt and limit to grab the next set (page count plus one)
  • discard the first key
  • apply the data to $scope

That would look something like the following:

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

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

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.

Also, check out this jsfiddle showing a simple paginate class.



来源:https://stackoverflow.com/questions/28558586/angularjs-fetch-records-for-pagination-from-firebase

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!