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.