Wednesday, April 13, 2016

How to make ngInfiniteScroll retrieve data by createdAt Descending

Leave a Comment

I'm using firebase to save posts that have the following data:

createdAt: "Sun Apr 03 2016 18:32:46 GMT-0300 (BRT)" 

What I'm trying to achieve is to get the most recent posts first and then load the older ones while the user scrolls down.

With posts retrieved using ngInfiniteScroll I'm being able to order desc using <div ng-repeat="post in posts | orderBy:'-createdAt'"> but ngInfiniteScroll keep returning the old posts first. I'm ordering but i'm ordering the older ones.

I already tried using the same logic ("-createdAt") in ngInfiniteScroll but it was not effective.


My js is pretty much this:

  var baseRef = new Firebase(FBURL).child("posts");   var scrollRef = new Firebase.util.Scroll(baseRef, "createdAt");   $scope.posts = $firebaseArray(scrollRef);   $scope.posts.scroll = scrollRef.scroll; 

Security and rules:

"posts": {           ".read": true,           ".indexOn": "createdAt",           "$post": {             ".read": true,             ".write": true,             "$other": {                ".validate": true             }          }       } 

2 Answers

Answers 1

Looks like you found your solution but you were on the right track piping with the orderBy but just try tweaking it a little. Try using orderBy:'+':true", where orderBy this says you want to order it by something and the +:true says order it where anything new is on top, where -:true would say order new content on the bottom. But you can look the angular docs for it here. So if where handling it on the HTML side it would look something like this ng-repeat="post in posts| orderBy:'+':true" or:

    <div ng-repeat="post in posts| orderBy:'+':true">            [....post info here]       </div> 

But give that a try, hope it helps.

Answers 2

After looking a little deeper at the available documentations I could find an ugly workaround here.

It is basically to use a negative timestamp and retrieve the createdAt normally (ascending).

So when saving the data I'm doing the following:

{   createdAt: Firebase.ServerValue.TIMESTAMP,   createdAtDesc: 0 - Date.now() } 

Still looking for a better solution.

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment