2013-03-22 2 views
0

각도 앱에 경로를 설정하기 만하면됩니다. 내가 /$http 전화의 뒤쪽으로 #/view/:id로 이동하면 첫 번째보기, List 프레젠테이션

의 목록을 얻기 위해 HTTP 호출을
function ListController($scope, $http) 
{ 
    $scope.error   = null; 
    $scope.presentations = null; 
    $scope.requesting  = true; 
    $scope.currentTitle  = '-1'; 
    $data = { 
     'type' : 'presentations' 
    }; 

    $http.post('resources/request.php', $data, {timeout:20000}) 
     .success(function(data, status, headers, config) 
     { 
      $scope.requesting = false; 
      $scope.presentations = data; 
     }) 
     .error(function(data, status, headers, config) 
     { 
      $scope.requesting = false; 
      log(status + ', data:" ' + data + '"'); 
     } 
     } 
    ); 
} 

내 노선은

angular.module('main',[]). 
    config(function($routeProvider) { 
    $routeProvider. 
     when('/', {controller:ListController, templateUrl:'resources/views/list.html'}). 
     when('/view/:id', {controller:VforumController, templateUrl:'resources/views/vforum.html'}). 
     otherwise({redirectTo:'/'}); 
    }); 

내가 가지고있는 문제입니다 다시 전화를받습니다. 앱에 처음 들어가서 처음으로로드 된 동일한 데이터를 참조하도록로드하려면 어떻게해야합니까?

각도 이외의 변수를 만들고 처음로드 된 데이터와 동일하게 설정하려고했습니다. 그런 다음 ListController에서 기본적으로 if data is null, do the $http call else set $scope.data = data을 수행했지만 작동하지 않았습니다. 목록보기가 비어 있습니다. $scope.data은 내 목록을 만드는 것입니다.

+0

당신을 했 컨트롤러에'$ route'를 넘겨주고'$ http.post()'앞에있는''$ routeParams' (http://docs.angularjs.org/api/ng.$routeParams)를 검사 해보십시오. 그럴 가치가있어. – couzzi

+0

나는 전에'$ routeParams'를 사용하지 않았습니다. 일반적으로'$ routes'. 이번이 처음입니다. 나는 이것에 대해 살펴볼 것입니다. 감사합니다. – Ronnie

답변

4

당신이 원하는 것은 각도에서 싱글 인 서비스입니다 :

.factory('myDataService', function ($http) { 
    var promise; 

    return function ($data) { 
    if (! angular.isDefined(promise)) { 
     promise = $http.post('resources/request.php', $data, {timeout:20000}); 
    } 

    return promise; 
    } 
}); 

는 그리고 지금 당신은 단순히 서비스를 호출 $http에 전화를 대체 할 수

function ListController($scope, myDataService) 
{ 
    // ... 

    myDataService($data).then(function success(response) { 
    $scope.requesting = false; 
    $scope.presentations = response.data; 
    }, function error(response) { 
    $scope.requesting = false; 
    log(status + ', data:" ' + response.data + '"'); 
    }); 
} 
+0

나는 이것이 정확하다고 생각하지 않습니다. '$ data'가 정의되지 않았습니다. 다시 말하지만, 전에 공장/서비스를 사용하지 않았습니다 : http://pastie.org/7084834 무엇이 잘못 되었습니까? '$ data'를 어떻게 서비스에 전달합니까? – Ronnie

+0

정적인지 여부에 따라 다릅니다. 여기서 정적으로 정의 했으므로 정적으로 서비스에 배치 할 수 있습니다. 동적으로 만들려면 공장에서 대신 함수를 반환 할 수 있습니다. 나는 후자의 경우에 대한 대답을 업데이트 할 것이다. –

+0

굉장해, 잘됐다! 'var 약속 '은 서비스가 무엇을 체크하고 있는가? 나는 앱이 $ http 호출을 두 번 호출하지 않도록 무엇을 만들고 있는지 잘 모르겠습니다. 즉,로드 된 데이터가 '약속'에 포함되어 있습니까? – Ronnie