AngularJS:控制器中返回的未定义值

时间:2014-06-24 15:36:24

标签: javascript angularjs http angularjs-factory

我正在使用angularJS来构建一个访问http资源的工厂。我可以在请求附近看到本地返回的数据,但数据不会在控制器中返回。这是我的工厂:

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;

});

我的控制器是:

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

1 个答案:

答案 0 :(得分:3)

$ http调用是一个ajax异步调用,这意味着您需要通过回调发送结果。这可能会有所帮助:

这是工厂:

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

return factory;

});

以下是如何使用它:

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