2014-10-06 3 views
0

AngularJS에서 새로 생겼습니다. 공장 기능에서 json 파일을 호출하려고했지만 내 var customers = []; 배열이 업데이트되지 않는다는 것을 보여줍니다. 도와주세요.Angular Factory에서 JSON 파일 호출이 작동하지 않습니다.

아래 코드는 제 코드입니다. 당신은 당신이 "$"HTTP 전에 서명을 넣어해야한다고 생각하지 마십시오

demoApp.factory('simpleFactory', ['$http', function($http){ 

    return { 

     getCustomer: function(){ 

      return $http.get("json/customers.json").then(
       function(response){ 
        var customers = []; 
        customers = response.data; 
       }, 
       function(error){ 
        console.log(error); 
       }); 

     } 

    } 
}]); 

답변

1

사용이 컨트롤러에서 :

demoApp.controller("emplyCtrl", function($scope, simpleFactory){ 
    simpleFactory.getCustomer().then(function(response){ 
     $scope.customers = response.data; 
    }); 
}); 

보기 (HTML)는 컨트롤러의 $scope에서 읽기 때문에, 컨트롤러의 어딘가에 $scope에 데이터를 넣어야합니다. 공장에서 설정 만하면 공장 출입이 가능합니다. 이 도움이

Here is the working Fiddle

희망!

+0

위대한 aarosil 당신은 챔피언입니다 !! –

3

이 같은 시도? 거기에 '$ http'는 직렬화 가능하다는 것을 나타내야한다고 생각합니다. 그래서 $ http는 이전 문자열 문에서 언급 한 것과 같은 방식으로 매개 변수 섹션에 명시되어야합니다.

또한 http 앞에 http를 사용하기 때문에 http 만 사용할 수 없습니다. 그렇지 않으면 각도 DLL이 코드를 인식하지 못합니다.

demoApp.factory ('simpleFactory'[ '$ HTTP'기능 ($ HTTP) {

var customers = []; 

$http.get("json/customers.json") 
    .success(function(data){ 
    customers = data; 
}); 

var factory = {}; 

factory.getCustomer = function(){ 
    return customers; 
}; 

return factory; 

}]);

여기 예를 살펴 : http://www.w3schools.com/angular/angular_http.asp

감사합니다,

+0

해결책을 시도했지만 작동하지 않았습니다. 나는 내 코드 pl을 업데이트하여 어떤 일이 잘못되었는지 알려준다. 데모 [http://jsfiddle.net/jkqcgcrw/2/] –

-1

:

var demoApp = angular.module("myApp", []); 

demoApp.factory('simpleFactory', ['$http', function($http){ 

    return { 

     getCustomer: function(){ 
      var customers = []; 
      return $http.get("http://www.w3schools.com/website/Customers_JSON.php") 
      .success(
       function(data){ 

        customers = data; 
       }, 
       function(error){ 
        console.log(error); 
       }); 
      console.log(customers) 
     } 

    } 

}]); 

demoApp.controller("emplyCtrl", function($scope, simpleFactory){ 
    $scope.customers = simpleFactory.getCustomer(); 
}); 

Demo Fiddle

관련 문제