【问题标题】:angular directive, http request and ng-repeat角度指令、http 请求和 ng-repeat
【发布时间】: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/ 作为占位符。

【问题讨论】:

标签: angularjs http angularjs-directive


【解决方案1】:
  1. 将数据分配给范围:$scope.data = result
  2. 内联定义您的模板:'template: &lt;div data-ng-repeat="item in data"&gt;//your stuff goes here&lt;/div&gt;'
  3. 或者将模板定义为 html 文件并为指令指定 `templateUrl:'

【讨论】:

  • @qua1ity - 可以显示您尝试过的代码吗?
  • 是的,编辑了我的帖子。基本上只是添加了 $scope.data = result.data 和你的模板
  • @qua1ity 控制台有任何错误吗?你是在result.data 中获取数据还是只是result
  • @qua1ity - 我认为数据来自result 本身...代码已更新
  • 啊是的..应该只是结果,它现在正在工作。谢谢
【解决方案2】:

我已经修好了你的小提琴。

  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}}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-15
    相关资源
    最近更新 更多