0

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
});
2
  • Could you please elaborate? Commented Jun 24, 2014 at 15:39
  • That call needs time to come back - so you're console statement fires while that call is still in progress - search on returning from an async call in an Angular factory Commented Jun 24, 2014 at 15:39

1 Answer 1

3

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;
    });
});
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.