Nevin
Nevin

Reputation: 375

Firebase, Storing snapshot datas to an array variable

Can I use ref.child('user').on('child_added',function()) to store what's inside a user to an array variable.

So this is my example,

$scope.samplearray = [];
ref.child('user').on("child_added", function(snapshot) {
  $scope.samplearray.name = snapshot.val().name;
  $scope.samplearray.age = snapshot.val().age;
});

then use that array to display it in my html using ng-repeat

Upvotes: 1

Views: 795

Answers (1)

David East
David East

Reputation: 32604

Child events in the Firebase Database are fired asynchronously, which is a problem out of the box in Angular 1.x. You will either need to to trigger the $digest loop directly after adding to the array or use AngularFire. I recommend you use AngularFire.

Vanilla SDK approach

function MyController($scope) {
  var ref = firebase.database.ref('items');
  var items = [];
  ref.on('child_added', function(snap) {
    $scope.$evalAsync(function() {
      var item = snap.val();
      // use a super private property to keep around the key
      item.__key = snap.key; 
      items.push(item);
    });
  });
}

AngularFire approach

function MyController($scope, $firebaseArray) {
  var ref = firebase.database.ref('items');
  // Handles all child events: added, removed, changed, moved
  $scope.items = $firebaseArray(ref);
}

Upvotes: 1

Related Questions