1

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

1
  • Did my answer help? Commented Jan 5, 2017 at 13:50

1 Answer 1

1

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.