I am writing an application where I need to display car inventory. I ping an API to get all cars matching search criteria such as Car Make, Model and Year. I need to display an image of each car along with the other information. Once the JSON data is available, it also has an ID (StyleID) for each car in my results that I need to use to make another API call to request images for that car.
After reading a few articles (such as this one) I figured I need to use a custom directive in order to query and insert each car's image in a specific spot when looping over the results.
I read this custom directive tutorial by Jim Lavin to create my sample. I was hoping that this approach will work however I must be missing something as it simply doesn't execute my custom directive and display the car image as I want it to.
Can someone please help?
Here's the plunker that shows my code: http://plnkr.co/edit/5DqAspT92RUPd1UmCIpn?p=preview
Here's the information about the specific media call to Edmunds API that I am trying to use.
And here's the URL to the media endpoint
Repeating my code :
My HTML code :
<div firstImageOfMyCar data-styleid="style.id"></div>
or
<firstImageOfMyCar data-styleid="style.id"></firstImageOfMyCar>
And here's my custom directive:
// 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);
});
}
});
}
};
});