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.

1

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

5 Comments

@qua1ity - is it possible to show the code you tried?
yeah, edited my post. Basically just added $scope.data = result.data and your template
@qua1ity any error in console? are you getting data in result.data or is it just result?
@qua1ity - I think the data is coming in result itself...code updated
Ah yeah.. should be just result, it's working now. Thanks
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}}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.