9

I created an array of users like so -

var ref = new Firebase(FIREBASE_URL + '/users');
var users = $firebaseArray(ref);

I have added objects to this and I want to loop through each of the users in this array. I know this is possible in the view using ng-repeat, but I need to do it in the controller. I have tried -

angular.forEach(users, function(user) {
    console.log(user);
})

But I get no result from this.

Ire Aderinokun
  • 145
  • 2
  • 7
  • 1
    See http://stackoverflow.com/questions/27049342/asynchronous-access-to-an-array-in-firebase/27050749#27050749. But also note the second snippet on this documentation page: https://www.firebase.com/docs/web/libraries/angular/guide/intro-to-angularfire.html#section-async-intro as it shows how best to debug data being loaded in an AngularJS/Firebase context: `
    {{ data | json }}
    `. `console.log` is not your best friend here.
    – Frank van Puffelen May 05 '15 at 20:50
  • 1
    Explained in the first page of the Angular guide and asked at least ten times here on Stack Overflow. – Kato May 06 '15 at 15:22

3 Answers3

29

Users probably isn't loaded by then, so you'll need to wait for it:

var ref = new Firebase(FIREBASE_URL + '/users');
var users = $firebaseArray(ref);

users.$loaded()
    .then(function(){
        angular.forEach(users, function(user) {
            console.log(user);
        })
    });

Here's the docs on it: https://www.firebase.com/docs/web/libraries/angular/guide/intro-to-angularfire.html#section-async-intro

Mathew Berg
  • 28,625
  • 11
  • 69
  • 90
2
var fbref = new Firebase(FIREBASE_URL + '/customers');
customers = $firebaseArray(fbref);

customers.$loaded()
.then(function(data){
    angular.forEach(data, function(value, key) {
        console.log('key='+key+', value='+value);
    })
});
CodecPM
  • 423
  • 6
  • 18
0

You can use the built-in $list attribute,
e.g. The below function counts users,

app.factory("Users", function($firebaseArray) {
  return $firebaseArray.$extend({             
    getUsers: function() {
      var user_count = 0;
      angular.forEach(this.$list, function(user) {
        user_count += 1;
        console.log(user);
      });
      return user_count;
    }
  });
})

and then to use it,

var userList = new Users(ref);
userList.$loaded().then(function() {
  userList.getUsers();
});
sbolel
  • 3,486
  • 28
  • 45
Arup Saha
  • 179
  • 1
  • 3
  • Note that @ArupSaha is [extending the $firebaseArray service](https://www.firebase.com/docs/web/libraries/angular/api.html#angularfire-extending-the-services) in this answer. The example is derived from the [documentation for `$firebaseArray.$extend`](https://www.firebase.com/docs/web/libraries/angular/api.html#angularfire-extending-the-services-firebasearrayextend). – sbolel May 06 '15 at 21:07