2

我正在尝试从来自对 API 的查询的 JSON 响应中获取特定对象。从响应中,我试图从被点击的结果中获取 ID,并将其传递到另外两个 http 查询的 url 中。

你能给我指出正确的方向以实现这一目标吗?

这是我当前的 services.js:

angular.module('myApp', ['ngResource'])

function Ctrl($scope, $http) {
var get_results = function(name) {
  if (name) {
    $http.get('http://api.discogs.com/database/search?type=artist&q='+ name +'&page=1&per_page=30').
      success(function(data3) {
        $scope.results = data3.results;
      });
  }
}
$scope.name = '';
$scope.$watch('name', get_results, true);



$http.get('http://api.discogs.com/artists/3823').
  success(function(data) {
      $scope.artist = data;
  });
$http.get('http://api.discogs.com/artists/3823/releases?page=1&per_page=200').
  success(function(data2) {
      $scope.releases = data2.releases;
  });
};

指令.js:

angular.module('myApp', ['ngResource'])

.directive('artistData', function() {

  return{
      restrict: 'E',
      template: '<div class="col-md-12"> \
                 <h1>Artist</h1>  \
                  {{artist.name}} \
                 <h1>Real name</h1> \
                  {{artist.realname}} \
                 <h1>Profile</h1> \
                  {{artist.profile}} \
                 <h1>Releases</h1> \
                  <ul><li ng-repeat="release in releases | filter:{ role: \'main\' }"> {{release.title}} ({{release.year}})</li></ul> \
                 <h1>Remixes</h1> \
                  <ul><li ng-repeat="release in releases | filter:{ role: \'remix\' }"> {{release.title}}</li></ul> \
                 </div>',
      replace: true
  };
 })  

我需要从其中获取 ID 的 JSON 响应的一部分:

1: {thumb:http://api.discogs.com/images/default-artist.png, title:Alva (2),…}
 id: 796507
 resource_url: "http://api.discogs.com/artists/796507"
 thumb: "http://api.discogs.com/images/default-artist.png"
 title: "Alva (2)"
 type: "artist"
 uri: "/artist/Alva+%282%29"

最后,相关的 HTML:

<ul>
    <li ng-repeat="result in results" ng-click="">{{result.title}}</li>
</ul>

我还创建了一个工作 Plunker。基本上,现在搜索工作正常,但指令在查询 url 中填充了定义的 ID (3823)。我需要做的是,一旦显示结果并单击结果,就可以获取此特定结果的 ID 并将其传递给其他两个 url。

所以而不是:

$http.get('http://api.discogs.com/artists/3823').

我本来有

$http.get('http://api.discogs.com/artists/'+artistid).
4

1 回答 1

2

在控制器中定义一个新方法,它将根据提供的数据获取数据id

$scope.getDetails = function (id) {
      $http.get('http://api.discogs.com/artists/' + id).
        success(function(data) {
            $scope.artist = data;
        });
      $http.get('http://api.discogs.com/artists/' + id + '/releases?page=1&per_page=200').
        success(function(data2) {
            $scope.releases = data2.releases;
        });
}

然后将上层函数传递给ng-click指令:

<li ng-repeat="result in results" ng-click="getDetails(result.id)">{{result.title}}</li>

Plunker上有工作版本。

于 2014-03-13T19:28:22.290 回答