AngularJS : Fetch records for pagination from Firebase

前端 未结 1 799
栀梦
栀梦 2020-12-04 03:16

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 = n         


        
相关标签:
1条回答
  • 2020-12-04 03:52

    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.

    0 讨论(0)
提交回复
热议问题