2

I'm trying to make a custom directive that gets data from a http request, and then through the template, loop the received data with ng-repeat.

I have made the http request working, but now I'm stuck. Not sure how to access the data in the template with ng-repeat.

My code:

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

Directive:

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");
        });
      }
    };
  }]);

Here is a jsfiddle with the same code: http://jsfiddle.net/g9zhdqw2/1/

I'm using https://jsonplaceholder.typicode.com/ as a placeholer.

qua1ity
  • 565
  • 2
  • 8
  • 27
  • You should read the answer to this question ,possibly in the following link http://stackoverflow.com/questions/16155542/dynamically-displaying-template-in-ng-repeat-directive-in-angularjs – Pritish Vaidya Sep 02 '16 at 11:52

2 Answers2

1
  1. Assign the data to the scope: $scope.data = result
  2. Define your template inline: 'template: <div data-ng-repeat="item in data">//your stuff goes here</div>'
  3. Or define a template as html file and specify `templateUrl:' for the directive
Developer
  • 6,240
  • 3
  • 18
  • 24
1

I have fixed your fiddle.

  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");
        });
      }
    };
  }]);

To finish it just add ng-repeat instead is the {{data}}

Itsik Mauyhas
  • 3,824
  • 14
  • 69
  • 114