2014-06-24 4 views
0

저는 angularJS를 사용하여 http 리소스에 액세스하는 팩토리를 작성합니다. 요청에 따라 로컬에서 반환되는 데이터를 볼 수 있지만 데이터가 컨트롤러에 반환되지 않습니다. 여기 내 공장은 다음과 같습니다 :AngularJS : 컨트롤러에서 반환 된 정의되지 않은 값

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

그것은 비동기 호출의

여기에 공장입니다! – tymeJV

+0

자세히 설명해 주시겠습니까? – user3486478

+0

전화가 다시 와야 할 시간이 필요합니다. 전화가 계속 진행되는 동안 '콘솔'문이 실행됩니다. Angular 공장에서 비동기 호출에서 복귀 할 때 검색하십시오. – tymeJV

답변

3

은 $ HTTP 호출하면 콜백을 통해 결과를 전송해야합니다 의미 아약스 비동기 호출입니다. 이 도움이 될 수

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

도움을 주셔서 대단히 감사합니다. 완벽하게 작동했습니다. – user3486478

관련 문제