我正在尝试从来自 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;
});
};
directives.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).
最佳答案
在 Controller 中定义一个新方法,它将根据提供的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 有工作版本.
关于javascript - 使用 AngularJS 从 JSON 响应 ($http) 获取对象并将其作为 ng-click 上的变量传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22387520/