角度指令,http请求和ng-repeat

时间:2016-09-02 11:44:17

标签: 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")
  .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/作为安置者。

2 个答案:

答案 0 :(得分:1)

  1. 将数据分配到范围:$scope.data = result
  2. 内联定义模板:'template: <div data-ng-repeat="item in data">//your stuff goes here</div>'
  3. 或者将模板定义为html文件,并为指令
  4. 指定`templateUrl:'

答案 1 :(得分:1)

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

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

相关问题