我试图从查询到API的JSON响应中获取特定对象。 从响应中,我试图从被点击的结果中获取ID,并将其传递到另外两个http查询的URL中。
你能指出我正确的方向来实现这个目标吗?
这是我当前的服务.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>
我还创建了working Plunker。基本上,现在搜索工作正常,但是指令在查询URL中填充了定义的ID(3823)。我需要做的是,一旦显示结果并单击结果,抓取此特定结果的ID并将其传递到其他两个URL。
所以而不是:
$http.get('http://api.discogs.com/artists/3823').
我有
$http.get('http://api.discogs.com/artists/'+artistid).
答案 0 :(得分: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;
});
}
然后将upper函数传递给ng-click
指令:
<li ng-repeat="result in results" ng-click="getDetails(result.id)">{{result.title}}</li>
Plunker上有工作版本。