【发布时间】:2016-09-02 20:22:36
【问题描述】:
我正在尝试制作一个自定义指令,从 http 请求中获取数据,然后通过模板,使用 ng-repeat 循环接收到的数据。
我已经使 http 请求正常工作,但现在我被卡住了。不确定如何使用 ng-repeat 访问模板中的数据。
我的代码:
<test-dir category="posts"></test-dir>
<test-dir category="comments"></test-dir>
指令:
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:http://jsfiddle.net/g9zhdqw2/1/
我使用https://jsonplaceholder.typicode.com/ 作为占位符。
【问题讨论】:
-
你应该阅读这个问题的答案,可能在下面的链接stackoverflow.com/questions/16155542/…
标签: angularjs http angularjs-directive