2016-09-02 4 views
2

http 요청에서 데이터를 가져 오는 사용자 지정 지시문을 만든 다음 템플릿을 통해 수신 된 데이터를 ng-repeat로 반복합니다.각도 지시어, http 요청 및 ng-repeat

나는 http 요청을 만들었지 만 지금은 붙어 있습니다. ng-repeat를 사용하여 템플릿의 데이터에 액세스하는 방법을 모릅니다.

내 코드 :

<test-dir category="posts"></test-dir> 
<test-dir category="comments"></test-dir> 

지침 : http://jsfiddle.net/g9zhdqw2/1/

나는 placeholer로 https://jsonplaceholder.typicode.com/을 사용하고 있습니다 :

여기
angular.module("myApp") 
    .directive('testDir', ['$http', function($http) { 
    return { 
     restrict: 'AE', 
     replace: true, 
     template: '<div ng-repeat="item in data"><li>{{item.body}}</li></div', 
     scope: { 
     category: '@category' 
     }, 
     controller: function($scope, $attrs) { 
     $http({ 
      method: 'GET', 
      url: 'http://jsonplaceholder.typicode.com/' + $attrs.category + '/1' 

     }).then(function(result) { 
      $scope.data = result.data; 

     }, function(result) { 
      alert("Error: No data returned"); 
     }); 
     } 
    }; 
    }]); 

가 같은 코드로 jsfiddle입니다.

+0

당신은 다음 링크를 http://stackoverflow.com/questions/16155542/dynamically-displaying-에 아마도이 질문에 대한 답을 읽어야입니다 ng-repeat를 추가 완료하려면 template-in-ng-repeat-directive-in-angularjs –

답변

1
  1. 범위에 데이터를 할당합니다 $scope.data = result
  2. 는 템플릿 인라인 정의 : 'template: <div data-ng-repeat="item in data">//your stuff goes here</div>'
  3. 을 또는 HTML 파일로 템플릿을 정의하고`templateUrl을 지정합니다 '지시어 내가 가진
+0

시도해 보았지만 작동하지 않습니다. – qua1ity

+0

@ qua1ity - 시도한 코드를 표시 할 수 있습니까? – Developer

+0

예, 내 게시물을 편집했습니다. 기본적으로 $ scope.data = result.data와 템플릿 – qua1ity

1

에 대한 바이올린을 고쳤다.

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


angular.module("myApp") 
    .directive('testDir', ['$http', function($http) { 
    return { 
     restrict: 'AE', 

     template: '{{data}}', //prints the data 
     scope: { 
     category: '@category' 
     }, 
     controller: function($scope, $attrs) { 
     $scope.data; 
     $http({ 
      method: 'GET', 
      url: 'http://jsonplaceholder.typicode.com/' + $attrs.category + '/1' 
     }).then(function(result) { 
      $scope.data = result; 
      console.log(result.data); 
     }, function(result) { 
      alert("Error: No data returned"); 
     }); 
     } 
    }; 
    }]); 

은 그냥 대신 {{data}}

+0

감사합니다. 작동합니다. – qua1ity