Angularjs angular指令、http请求和ng repeat

Angularjs angular指令、http请求和ng repeat,angularjs,http,angularjs-directive,Angularjs,Http,Angularjs Directive,我试图创建一个自定义指令,从http请求获取数据,然后通过模板,使用ng repeat循环接收到的数据 我已经让http请求工作了,但是现在我被卡住了。不确定如何使用ng repeat访问模板中的数据 我的代码: <test-dir category="posts"></test-dir> <test-dir category="comments"></test-dir> 指令: angular.module("myApp") .dire

我试图创建一个自定义指令,从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");
        });
      }
    };
  }]);
angular.module(“myApp”)
.directive('testDir',['$http',function($http){
返回{
限制:“AE”,
替换:正确,
模板:'
  • {{item.body}}
  • 将数据分配给作用域:
    $scope.data=result
  • 内联定义模板:
    'template://你的东西放在这里'
  • 或者将模板定义为html文件,并为指令指定“templateUrl:”

  • 我把你的小提琴修好了

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

    要完成它,只需添加
    ng repeat
    ,取而代之的是
    {{data}

    你应该阅读这个问题的答案,可能在下面的链接@qua1ity-是否可以显示你尝试的代码?是的,编辑了我的文章。基本上只是添加了$scope.data=result.data和你的template@qua1ity控制台中有错误吗?您是在
    result.data
    中获取数据,还是仅仅是
    result
    ?@quality-我想数据是从
    result
    本身来的…代码更新了啊是的..应该只是结果,它正在工作。谢谢