在 AngularJS 中使用 API

Working with APIs in AngularJS

我正在尝试创建一个显示多个 'users' 的 'channel' 数据的布局。我正在使用的 API 需要先查询以获取用户名列表,然后再查询每个用户以获取频道信息。

我尽了最大的努力,但最终以失败告终。

这是一个plunker...

HTML:

  <body ng-controller="ChannelCtrl">
    <channel ng-repeat="username in names" data-username="{{ username }}">a</channel>
  </body>

var app = angular.module('app', []);

app.controller('ChannelCtrl', ['$scope', 'channelService', function($scope, channelService) {
  $scope.names = channelService.getUsers();
}]);

JS:

app.factory('channelService', ['$http', function($http) {
  return {
    getUsers: getUsers,
    getChannel: getChannel
  };

  function getChannel(name) {
    $http.get('api/channels'+name+'Channel.json')
    .success(function(data, status, headers, config) {
      console.log(data);
      return data;
    });
  }

  function getUsers() {
    $http.get('api/users.json')
    .success(function(data, status, headers, config) {
      console.log(data);
      return data;
    });
  }
}]);

app.directive('channel', ['channelService', function(channelService) {
  return {
    restrict: 'E',
    template: "Hello {{ channel }}<br>",
    link: function(scope, element, attrs) {
      scope.channel = channelService.getChannel(attrs.username);
      console.log('channel::link', scope.channel);
    }
  };
}]);

您必须在您的服务中 return 您的 $http.get 功能。之后要访问控制器中的数据,您必须调用 $http 成功函数并将数据响应分配给您的范围变量。这是因为 $http.get 函数的异步行为。

更新

我已经更新了 plunker,所以它会显示您想要的输出。您不必在指令中使用 attrs,因为您可以从 ng-repeat 元素 (Scope Chain) 访问范围数据。如果您没有在指令定义对象中设置 scope 属性,这是默认行为。 我还删除了评论中提到的您服务中不必要的成功函数调用。

控制器:

app.controller('ChannelCtrl', ['$scope', 'channelService', function($scope, channelService) {
  channelService.getUsers().success(function(users) {
    $scope.users = users; 
  });
}]);

服务:

app.factory('channelService', ['$http', function($http) {
  return {
    getUsers: getUsers,
    getChannel: getChannel
};

 function getChannel(name) {
   return $http.get('api/channels/' + name + 'Channel.json');
 }

 function getUsers() {
   return $http.get('api/users.json');
 }
}]);

指令:

app.directive('channel', ['channelService', function(channelService) {
  return {
    restrict: 'E',
    template: "Hello {{ channel }}<br>",
    link: function(scope, element, attrs) {
       channelService.getChannel(scope.user.username).success(function(data) {
       scope.channel = data[0].channel;
     });
  }
};
}]);

Updated Plunker