Hugh Hou
Hugh Hou

Reputation: 2374

get nested object length in an angularFire array in Firebase

I have a Firebase structure like this:

user {
  uid {
    Lessons {
      lid1 {
         Title: ...
          }
      lid2 {
         Title: ...
          }
     }
   }
  }

I want to use AngularFire to convert user as array so I can filter them using Angular like this:

var usersRef = new Firebase($rootScope.baseUrl + "users"); 
var userListfb = $firebase(usersRef).$asArray();

The problem is, I also need the number of child of the Lessons object. When I log the userListfb, it is an array. But inside the array, the Lessons node still an object. I can not user length to get its length. What is the correct way to find out the number of child of the Lessons Node with Firebase AngularFire?

Edit 1 According to Frank solution, I got an infinite loop (digest circle error from AngularJS). The problem is, I will not know the "uid" key. I need to loop it in the first array to get the uid into the second firebaseArray. Let's say I have a ng-repeat="user in users" in the view and call this on view level in each repeat:

{{getLessonLength(user.uid)}}

Then in the controller, I have this function:

$scope.users = $firebaseArray($scope.usersRef);

$scope.getLessonLength = function (uid) {

        var userRef = $rootScope.baseUrl + "users/" + uid + "/lessons/";

        var lessonsNode = $firebaseArray(new Firebase(userRef));

        return lessonsNode.length;
    }
}

And it throw this error: Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting! Watchers fired in the last 5 iterations: []

All I want it is something like var lessonsCount = snapshot.child('lessons').numChildren() in regular Firebase .on('child_added' ...), the numChildren() function in FirebaseArray. Please help!

Upvotes: 1

Views: 2881

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598728

AngularFire contains quite some code to ensure that an ordered collection in your Firebase maps correctly to a JavaScript array as Angular (and you) expect it.

If you have a reference to a specific user, you can just create a new sync ($firebase) and call $asArray on that.

var usersRef = new Firebase($rootScope.baseUrl + "users"); 
var userListfb = $firebase(usersRef).$asArray();
var uid1LessonsRef = userRef.child('uid1').child('Lessons');
var uid1LessonsArray = $firebase(uid1LessonsRef).$asArray();
uid1LessonsArray.$loaded().then(function(arr) {
    console.log('Loaded lessons, count: '+arr.length);
});

The data will only be synchronized once, no matter how many references you create to it.

Upvotes: 1

Related Questions