qua1ity qua1ity - 1 year ago 115
AngularJS Question

angular directive, http request and ng-repeat

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('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) {
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.

Answer Source
  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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download