2015-01-10 3 views
0

아약스 요청을하는 지시문이 있습니다. 내가 여기 같은 $ 제한 시간 안에 그것을 포장 할 때까지 작동하지 것 :

return { 
     restrict: 'E', 
     scope : { 
      param1: '=', 
      param2: '=' 
     }, 
     templateUrl: "teams/views/myDirective.html", 
     link: function($scope){ 
      $timeout(function(){ 
       $http.get(endPointUrl) 
        .success(function(result){ 
         console.log(result) 
        }) 
        .error(function(err){ 
         console.log(err); 
        }); 
      }, 0); 
     } 
    }; 

을 누군가가 왜 생각을 가지고 있습니까? 답을 미리 감사드립니다.

+0

, 그것을 작동합니다. 게시하지 않은 코드에서 다른 작업이 진행 중입니다. –

+0

사실, 아약스 요청을하는 많은 지시문 (5-6)이 있습니다. 정상적인 데이터 흐름의 동작에 영향을 미칠 수 있다고 생각합니까? – Iamisti

+0

"정상적인 데이터 흐름"이란 무엇을 의미하는지 모르겠습니다. 콘솔에 오류가 있습니까? Btw, 여기에 귀하의 [코드] (http://plnkr.co/edit/1yNlxnZsyudg2mwnOqXp?p=preview)가 작동하는 설명 목적으로 조정되었습니다. –

답변

1

$http 호출은 단지 약속을 반환합니다. 다음 코드는 도움이됩니다. 이상적으로, 작업과 같은 데이터를 가져 오는 작업은 지시문의 링크 기능 대신 서비스에서 수행해야합니다.

app.service('myService', ['$http', 
    function($http) { 
    this.getData = function() { 
     return $http({ 
     method: 'GET', 
     url: 'http://httpbin.org/get', 
     headers: { 
      'Content-Type': "application/json" 
     } 
     }). 
     success(function(data, status) { 
     return data; 
     }). 
     error(function(data, status) { 
     return "Request Failed"; 
     }); 

    } 
    } 
]); 

app.directive('appDirective', ['myService', 
    function(myService) { 
    return { 
     link: function($scope) { 
     myService.getData().then(function(data) { 
      $scope.name = 'User, Data fetched as: ' + JSON.stringify(data); 
     }) 
     } 

    } 
    } 
]) 

작업 예 : 뭔가를 누락하지 않는 한 http://plnkr.co/edit/stdJxAnHINORI06pPZJX?p=preview

관련 문제