0

I'm new to AngularJS so please be gentle.

I'm trying to fetch data from firebase using a factory .on('value',..) and pass it through to the controller. It seems to be a problem with passing the object itemObj through to the controller, because line 25 console.log(itemObj.name) shows us what we're looking for.

the factory:

'use strict';

angular.module('MyApp')
.factory('MenuItems', function(FIREBASE_ROOT) {
    var ref = new Firebase(FIREBASE_ROOT);
    var refMenu = ref.child('/menu/');

    // get today's date in dd-mm-yyyy
    var today = new Date();
    var dd = today.getDate();
    var mm = today.getMonth()+1; //January is 0!
    var yyyy = today.getFullYear();
    if(dd<10) { dd='0'+dd; } 
    if(mm<10) { mm='0'+mm; }
    today = dd+'-'+mm+'-'+yyyy;


  var itemObj = null;


    return  {
    items:  function() {
              refMenu.child(today).on('value', function(snapshot) {
              itemObj = snapshot.val();
              console.log(itemObj.name);
              return itemObj;
              });
            }
          };
});

the controller:

'use strict';

angular.module('MyApp.controllers').controller('DashboardCtrl', ['$scope', '$firebase', 'FIREBASE_ROOT', 'Auth', 'User', 'MenuItems',
function($scope, $firebase, FIREBASE_ROOT, Auth, User, MenuItems) {
    var ref = new Firebase(FIREBASE_ROOT);
    var refCart = ref.child('/cart/');

    $scope.numberItems = 0;
    var user = Auth.currentUser;
    $scope.item = MenuItems.items();
    console.log(MenuItems.items());

}]);
aiouy
  • 3
  • 1
  • possible duplicate of [Asynchronous access to an array in Firebase](http://stackoverflow.com/questions/27049342/asynchronous-access-to-an-array-in-firebase) – Frank van Puffelen Dec 27 '14 at 00:14

1 Answers1

0

The issue with your code is that in the factory, items function will return nothing as it would immediately complete its execution after attaching the event handler.

The return itemObj; is inside the event callback and will not be passed to items.

I am not an expert on Firebase but I guess you need to use promises to make this scenario work for you. I googled and found that there is a version of Firebase for AngularJS.

Check the link: https://www.firebase.com/blog/2013-03-29-firebase-bindings-for-angular.html

Also this link: http://tamas.io/angularjs-firebase-angularfire/

Jay
  • 1,478
  • 1
  • 10
  • 9
  • where should I put it? I tried bringing it outside: `return { items: function() { refMenu.child(today).on('value', function(snapshot) { itemObj = snapshot.val(); console.log(itemObj.name); }); return itemObj; } };` – aiouy Dec 26 '14 at 20:02
  • I wasn't able to get it working using these commands but I did realize I'm using an outdated version of angularFire & firebase. The *updated* AngularFire calls make it much easier to get data from firebase so that should do it. Thanks Jay. – aiouy Dec 27 '14 at 21:20