Search code examples
angularjsfirebasefirebase-realtime-databasedata-retrieval

Firebase and AngularJS, How to retrieve a value from a firebaseArray


It seems to be very very simple. But I can't do it. I just want to get a value of my Firebase DB in my controller. The Firebase Database is like this:

users {
    30549545 {
        name: "Marcelo"
        lastName: "Forclaz"
        years: 24
    }
}

In my controller I wrote the following code:

app.controller('usersCtrl', function($scope, $firebaseArray) {
    var ref = firebase.database().ref('users');
    $scope.userdata = $firebaseArray(ref);
});

In the ngRepeat of the HTML code the iteration works fine. But I need to get the "years" value in my controller to use it to another command, ¿How can I do it? I've tried of several deferents ways but I didn't get the wished result. I realized that retrieving data from Firebase width AngularJS is not so easy than make it width simple and pure JavaScript.


Solution

  • Finally, I've got it!

    $scope.userdata.$ref().once('value', function(snap) {
        angular.forEach(snap.val(), function(index)) {
            console.log(index.years)
        }
    }