【发布时间】:2014-09-23 16:45:05
【问题描述】:
我正在编写一个需要显示汽车库存的应用程序。我 ping 一个 API 以获取所有符合搜索条件的汽车,例如汽车制造商、型号和年份。我需要显示每辆车的图像以及其他信息。一旦 JSON 数据可用,它还会在我的结果中为每辆汽车提供一个 ID (StyleID),我需要使用它来进行另一个 API 调用以请求该汽车的图像。
在阅读了几篇文章 (such as this one) 后,我想我需要使用自定义指令,以便在循环结果时查询并将每辆车的图像插入特定位置。
我阅读了 Jim Lavin 的 custom directive tutorial 来创建我的示例。我希望这种方法能够奏效,但是我必须遗漏一些东西,因为它根本不执行我的自定义指令并按照我的意愿显示汽车图像。
有人可以帮忙吗?
这是显示我的代码的 plunker: http://plnkr.co/edit/5DqAspT92RUPd1UmCIpn?p=preview
这是关于我正在尝试使用的 specific media call to Edmunds API 的信息。
重复我的代码:
我的 HTML 代码:
<div firstImageOfMyCar data-styleid="style.id"></div>
或
<firstImageOfMyCar data-styleid="style.id"></firstImageOfMyCar>
这是我的自定义指令:
// Custom Directive to get first image of each car.
app.directive('firstImageOfMyCar', function() {
return {
restrict: "E",
link: function(scope, elm, attrs) {
// by default the values will come in as undefined so we need to setup a
// watch to notify us when the value changes
scope.$watch(attrs.styleid, function(value) {
//elm.text(value);
// let's do nothing if the value comes in empty, null or undefined
if ((value !== null) && (value !== undefined) && (value !== '')) {
// get the photos for the specified car using the styleID.
// This returns a collection of photos in photoSrcs.
$http.get('https://api.edmunds.com/v1/api/vehiclephoto/service/findphotosbystyleid?styleId=' + value + '&fmt=json&api_key=mexvxqeke9qmhhawsfy8j9qd')
.then(function(response) {
$scope.photoSrcs = response.photoSrcs;
// construct the tag to insert into the element.
var tag = '<img alt="" src="http://media.ed.edmunds-media.com' + response.photoSrcs[0] + '" />" />'
// insert the tag into the element
elm.append(tag);
}, function(error) {
$scope.error3 = JSON.stringify(error);
});
}
});
}
};
});
【问题讨论】:
-
为什么不将图像 URL 添加到您的范围,然后像处理其余数据一样将其添加到模板中?
标签: javascript json angularjs api rest