Currently, I am in the process of developing an application that requires me to showcase a car inventory. To achieve this, I utilize an API to fetch all cars that match specific search criteria including Car Make, Model, and Year. My objective is to exhibit an image of each car alongside other pertinent information. In addition to obtaining JSON data, there is also a unique ID (StyleID) assigned to each car in the results which prompts me to initiate another API call to procure images for each individual car.
Having explored various articles on the topic, such as the one linked here, it became apparent that implementing a custom directive is necessary in order to retrieve and insert the image of each car at a specified location while iterating through the results.
In my quest for a solution, I came across Jim Lavin's tutorial on creating a custom directive. Despite following the guidelines provided, I seem to have missed a crucial step as my custom directive fails to execute properly, resulting in a lack of display for the car images as intended.
Seeking guidance from others who may be more experienced in this area, I kindly ask for assistance.
To provide further context, here is a link to the Plunker showcasing my code implementation:
Additonally, detailed information regarding the media call to the Edmunds API can be found here.
For those interested, the URL to access the media endpoint has been provided.
Reiterating my code setup:
HTML syntax utilized:
<div firstImageOfMyCar data-styleid="style.id"></div>
or
<firstImageOfMyCar data-styleid="style.id"></firstImageOfMyCar>
Implementation of the custom directive:
// Custom Directive for fetching the primary image of each car.
app.directive('firstImageOfMyCar', function() {
return {
restrict: "E",
link: function(scope, elm, attrs) {
// setting up a watcher to detect changes in the value
scope.$watch(attrs.styleid, function(value) {
//elm.text(value);
// only proceed if the value is not empty or undefined
if ((value !== null) && (value !== undefined) && (value !== '')) {
// fetching photos for the specified car using the StyleID
// returning 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;
// constructing the tag to inset into the element
var tag = '<img alt="" src="http://media.ed.edmunds-media.com' + response.photoSrcs[0] + '" />" />'
// inserting the tag into the element
elm.append(tag);
}, function(error) {
$scope.error3 = JSON.stringify(error);
});
}
});
}
};
});