3

I have completely stumped myself with trying to instantiate a factory in my controller. No matter what I do it seems my factory ('FBRetrieve') is undefined. It must be something very simple, but can't seem to find a solution via S/O search/google/angulardocs.

app.js

var legalmvc = angular.module('legalmvc', ['ngRoute','FireBaseService']);

factory.js

angular.module("FireBaseService", []).factory('FBRetrieve', function(){
    var biblioData = new Object();


    biblioData.getData = function(type){
        var biblioRef = new Firebase('https://legalcitator.firebaseio.com/'+type);

        biblioRef.on('value', function(data) {
            if (data.val() === null) {
                console.log("ERROR");
                return;
            }
            console.log(data.val());
            biblioData = data.val();


        });

        return biblioData;

    };

});

and in the controller I'm instantiating with something like this:

legalmvc.controller('FormCtrl',["$scope","FBRetrieve", function ($scope, FBRetrieve) {

    $scope.FBRetrieve = FBRetrieve.getData('case');

..... 
zazou
  • 197
  • 3
  • 10

1 Answers1

3

getData is asynchronous operation, it means that response is not yet available when you try to return it. Instead you should use callback of deferred pattern (more natural in this case):

biblioData.getData = function(type) {

    var biblioRef = new Firebase('https://legalcitator.firebaseio.com/'+type),
        deferred = $q.defer(); // remember to inject $q service into factory 

    biblioRef.on('value', function(data) {
        if (data.val() === null) {
            deferred.reject('ERROR');
        }
        deferred.resolve(data.val());
    });

    return deferred.promise;
};

Then you would use it in controller:

FBRetrieve.getData('case').then(function(data) {
    $scope.FBRetrieve = data;
}, function() {
    // handle error
});

Also learn about this common problem and solution.

Community
  • 1
  • 1
dfsq
  • 191,768
  • 25
  • 236
  • 258