Search code examples
javascriptangularjshttpangularjs-factory

AngularJS : Undefined value returned in controller


I am using angularJS to build a factory that accesses a http resource. I can see the data being returned locally near the request but the data is not returned in the controller. Here is my factory:

myNameSpace.factory('simpleFactory', function ($http) {
var factory = {};
var customers = [];
factory.getCustomers = function () {
    $http.jsonp('http://URL&callback=JSON_CALLBACK').success(function (data) {
        customers = data;
        return customers;
    })
}

return factory;

});

My controller is:

myNameSpace.controller('DetailsController', function ($scope, $http, simpleFactory) {
var cust = simpleFactory.getCustomers();
$scope.CustomerData = simpleFactory.getCustomers();
console.log(cust); //The value that is display here is undefined
});

Solution

  • The $http call is an ajax asynchronous call which means you'll need to send the result through a callback. This may help:

    Here's the factory:

    myNameSpace.factory('simpleFactory', function ($http) {
    var factory = {};
    factory.getCustomers = function (callback) {
        $http.jsonp('http://URL&callback=JSON_CALLBACK').success(callback);
    }
    
    return factory;
    
    });
    

    Here's how to use it:

    myNameSpace.controller('DetailsController', function ($scope, $http, simpleFactory) {
        simpleFactory.getTopOffenders(function(offenders) {
            $scope.topoffendersData = offenders;
        });
    });