0

I have an alarm app using Firebase where, when the user uses it the first time, 3 sample tasks are added to the list and saved to the Firebase. In order to prevent these sample tasks added again, my code is supposed to check the snapshot (representation of data in Firebase) and skip the $scope.data.$add part. However, it keeps adding additional 3 samples every time the page is refreshed.

Tracing the code execution in the Chrome Dev tool, the ref.once() block is skipped when the page is refreshed, and therefore leaves the snapshot undefined, which explains why the sample tasks are added again and again.

Please advise what I'm missing. Thanks!

ref.once('value', function(snapshot) {

  $scope.total = snapshot.numChildren();
});


if ($scope.total == 0) {
  $scope.list = [
    {content: "9am", event: "Sam", bgColor: "#b58900"},
    {content: "9:30am", event: "Holley", bgColor: "#cb4b16"},
    {content: "10:30am", event: "Nick", bgColor: "#d33682"}

  ];

  $scope.list.forEach(function(item){
    $scope.data.$add({'content':item.content, 'event':item.event, 'bgColor':item.bgColor});
  });
}
Jason O.
  • 3,168
  • 6
  • 33
  • 72
  • 1
    See http://stackoverflow.com/questions/27049342/impossible-to-access-array-with-angular-and-firebase – Kato Mar 01 '15 at 20:07

1 Answers1

1

Moved the if ($scope.total == 0) { ... } block into ref.once('value', function(snapshot) { .. }, and it works. The issue was that my code didn't wait for the callback from firebase. Hope this helps someone.

Jason O.
  • 3,168
  • 6
  • 33
  • 72
  • 1
    Great to hear that you found the solution *and* the problem! This is indeed a typical case of the asynchronous nature of data loading biting you. And indeed the solution is usually to do what you did: move the code that depends on the data *into* the callback. Don't forget to accept your self-answer once the system allows it. – Frank van Puffelen Mar 01 '15 at 01:18
  • Thank you, Kato and Frank for your helpful comments. – Jason O. Mar 02 '15 at 02:03