2013-05-24 1 views
1

저는 Angular.js로 시작했는데 캐시 된 데이터를 표시하고이를 가져온 데이터로 대체하는 팩토리를 설정하는 방법을 파악하려고합니다. 일단 수신되면 REST 서비스.캐시 된 데이터로 angularjs 팩토리를 설정하는 올바른 방법

이것을 테스트하려면 "캐시 된"데이터를 하드 코딩해야합니다. 데이터가 수신되면 $ scope.directory 변수가 서버에서받은 최신 데이터로 업데이트되기를 원합니다.

app.factory('directoryFactory', function ($http) { 
var factory = {}; 
factory.directory = [{name: "Test", ext: "123"},{name: 'Bob', ext: "234"}]; 

init(); 
function init() { 
    $http({ 
     method: 'GET', 
     url: '{restapiURL}' 

    }) 
     .success(function (data, status, headers, config) { 
      factory.directory=data; 
     }) 
     .error(function (data, status, headers, config) { 
      console.log('directory fail'); 
     }); 
} 

} 

내 컨트롤러는 다음과 같은 코드가 있습니다 : 나는

여기 내 공장 코드의 얻을 수 있습니다 내보기에서

$scope.directory = directoryFactory.directory; 

을, 나는 모든 사람을 나열하는 NG-반복 사용 및 확장.

데이터를 수신하면보기를 업데이트하고 싶습니다. 공장 데이터 변경 사항을 보는 올바른 방법은 무엇입니까?

+0

[이 예제] (http://stackoverflow.com/questions/12505760/angularjs-processing-http-response-in-service)는 http 응답을 반환하는 데 도움이되도록'.then '를 사용합니다. [이 포스트] (http://www.benlesh.com/2013/02/angularjs-creating-service-with-http.html)는 꽤 좋은 튜토리얼을 보여주고'$ q' 메소드를 포함하고 있습니다. 나중에 시간이 있다면 나는 plunk를 게시 할 수 있지만 이것들은 시작할 좋은 장소입니다. – rGil

+0

$ http 호출에서 디렉토리 응답을 얻을 수 있지만 새 데이터를 표시하려면 컨트롤러에서 다음을 가져야합니다. $ scope.directory = directoryFactory.directory(); $ timeout (function() { $ scope.directory = directoryFactory.directory(); }, 2000); 이것에 대한 설명 : directoryFactory.directory가 업데이트 될 때 $ scope.directory를 트리거하여 최신 값을 찾는 방법은 무엇입니까? – jloosli

+0

하루가 끝날 때 $ 브로드 캐스트를 사용하여 컨트롤러에 두 번째 데이터 집합이로드되었음을 알리게되었습니다. – jloosli

답변

2

$scope.directory은 성공과 실패시 2 개의 처리기가 포함 된 약속입니다.

공장 : $http 비동기이기 때문에 응답은 당신이 then()

을 사용하는 경우 "약속"경우에 대해 알려 드리겠습니다 올하지만해야 할 때, 당신은 여기에 POST의 예입니다하지만 같은 흐름 모른다 : 컨트롤러

myModule.factory('ajax_post', ['$http', function(_http) { 

var path = 'src/php/data.ajax.php'; 

return{ 
    init: function(jsonData){ 
     var _promise= _http.post(path, 
      jsonData 
      ,{ 
       headers: { 
        'SOAPActions': 'http://schemas.microsoft.com/sharepoint/soap/UpdateListItems' 
       } 
      } 
      );    
     return _promise; 
    } 
    } 
}]); 

:

var _promise= ajax_post.init(jsonData); 

    _promise.then(function (result) { 

     //do something with your result 
    }, 
    function (error) { 
     alert(error.message); 
    } 
    ); 
관련 문제