Utilizing the power of AngularJS in conjunction with the Edmunds Media API to retrieve stunning

Scenario: Utilizing a Rails application and $http.get in AngularJS to retrieve photos from the Edmunds.com MEDIA API.

GOAL: To use ng-repeat to cycle through the vehicle photos.

ISSUE: While I am able to successfully fetch a single image, I am struggling to loop through the photos array and display all the images. Any assistance on how to achieve this is greatly appreciated.

I apologize for any confusion in my explanation, and thank you for your help!

index.html:

   <h1> Wheel Tire Family </h1>
   <!--  CAR IMAGES  -->
   <div ng-init="carImages">

     <img src="https://media.ed.edmunds-media.com/{{carImages}}">

   </div>   

catalog_controller.js:

$scope.photos = {};
$scope.carImages = {};

//GET the edmunds media api for the
//Make Model Year photos

$http.get("https://api.edmunds.com/api/media/v2/audi/a3/2015/photos?title=&category=exterior&provider=oem&width=1280&shottype=S&pagenum=1&pagesize=10&view=basic&api_key=api_key&fmt=json")
    .success(function (data) {
        var photos = data;
        console.log(photos);
        $scope.carImages = photos.photos[0].sources[0].link.href;
        console.log($scope.carImages);
        });

Answer №1

Could a possible solution look something like this?

angular

.success(function (data) {
    $scope.carImages = data.photos;
});

html

<div ng-repeat="carImage in carImages">
    <img ng-src="https://media.ed.edmunds-media.com/{{carImage.sources[0].link.href}}">
</div>

This code snippet is designed to iterate through the images and extract the first "source" link. For better practice, it's advisable to utilize ng-src instead of src.

Answer №2

If you're looking to integrate Jquery with AngularJS, I have some useful code snippets that might come in handy.

For fetching Vehicle Details (New, Used, Future) using Jquery, you can utilize the following code snippet:

     <!--Form Details to display year/make/model in dropdown -->
     <form method="POST" action="one123.php">
   <select id="ajYears" name="ajYears">
    </select>
     <select id="ajMakes" name="makes" disabled="disabled">
        <option>Select Make</option>
    </select>
    <select id="ajModels" name="models" disabled="disabled">
        <option>Select Model</option>
    </select>
    <select id="ajStyles" name="styles" disabled="disabled">
        <option>Select Trim</option>
    </select>
    <input type="submit" value="submit">
   </form>

     <!--Script to fetch details from API-->
     <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
     <script>
 jQuery.noConflict();
     </script>

      <!-- js code -->
       <script>
   var protoCall = "https://";
     var host = "api.edmunds.com";

    // Please ensure to replace the placeholder with your own API KEY
var apiKey = "API KEY";
var fmt = "json";
var standardParams = "&fmt=" + fmt +  "&api_key=" + apiKey + "&callback=?";
var $yearSelect = jQuery('#ajYears');
var $makeSelect = jQuery('#ajMakes');
var $modelSelect = jQuery('#ajModels');
var $styleSelect = jQuery('#ajStyles');

// Attaching event listeners on document.ready.
jQuery(function(){

    $yearSelect.on('change', function() { getMakeModelsByYear()});
    $makeSelect.on('change', function() { enableModelDropdown() });
    $modelSelect.on('change', function() { getStyles() });

    // Building the year drop down.
    ajEdmundsBuildYear();

});

// Method to populate the year drop down.
function ajEdmundsBuildYear()
{
    var baseYear = 1990,
        endYear = new Date().getFullYear();
    $yearSelect.empty();
    $yearSelect.append('<option value="-1">Select Year</option>');
    for(var yyyy=baseYear; yyyy<=endYear; yyyy++)
    {
        $yearSelect.append('<option value="' + yyyy + '">' + yyyy +'</option>');   
    }
}

// Fetching makes and models based on selected year.
function getMakeModelsByYear()
{
    var year = $yearSelect.val(),
        endPoint = "/api/vehicle/v2/makes",
        view = "basic",
        options = "year=" + year + "&view=" + view + standardParams,
        postURL = protoCall + host + endPoint + "?" + options;
    jQuery.getJSON(postURL,
        function(data) {
             // Clear make drop down, add first option, and remove 'disabled' attribute.
             $makeSelect.empty();
             $makeSelect.append('<option value="-1">Select Make</option>');
             $makeSelect.removeAttr('disabled');
             $modelSelect.empty();
             $modelSelect.append('<option value="-1">Select Model</option>');

             // Loop through makes and their models, populate corresponding dropdowns.
             jQuery.each(data.makes, function(i, val) {
                  make = data.makes[i];
                  $makeSelect.append('<option value="' + make.niceName + '">' + make.name + '</option>');
                  jQuery.each(make.models, function(x, val){   
                       model = make.models[x];
                       $modelSelect.append('<option make="' + make.niceName +'" value="' + model.niceName + '">' + model.name + '</option>');                 
                  });
             });
        });
}

// Update model dropdown to show only matching models for selected make.
function enableModelDropdown()
{
    var make =  $makeSelect.val();
    $modelSelect.removeAttr('disabled');
    $modelSelect.find('option').not('[value="-1"]').hide();
    $modelSelect.find('option[make=' + make + ']').show();
}

// Retrieve styles related to selected year, make, and model.
function getStyles()
{
    var year = $yearSelect.val(),
        make = $makeSelect.val(),
        model = $modelSelect.val(),
        endPoint = "/api/vehicle/v2/" + make + "/" + model + "/" + year + "/styles",
        view = "basic",
        options = "view=" + view + standardParams,
        postURL = protoCall + host + endPoint + "?" +  options;
    jQuery.getJSON(postURL,
        function(data) {
             $styleSelect.empty();
             $styleSelect.removeAttr('disabled');
             $styleSelect.append('<option value="-1">Select Style</option>');
             jQuery.each(data.styles, function(i, val) {
                  style = data.styles[i];
                  $styleSelect.append("<option value='" + style.id + "'>" + style.name + "</option>");
             });
        });
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Set the camera to view the world from a y-coordinate of 0 and descend

How can I make the top of the render area in Three.js point to y=0 in the world? I also want the camera to look straight (lookAt) These are my current values: camera = PerspectiveCamera camera.position.z = 1895.8448868133867 camera.fov = 20 screen.width ...

Having trouble with ASP.NET Core MVC Ajax call not sending parameters to the API controller method?

I'm having trouble calling an API controller method using ajax and passing parameters. The api method gets called, but the values come through as null in the controller method. Interestingly, using the same ajax call, another controller (not the api ...

Learn how to display a web page in a tab view similar to the toggle device toolbar option

Is it possible to simulate the toggle device toolbar of a web page using JavaScript? https://i.stack.imgur.com/M9oB0.png For example, can we set up a webpage to always display in tab or mobile view like on YouTube? ...

Issue with updating data variable from watcher on computed property in Vue.js with Vuex

Snippet: https://jsfiddle.net/mjvu6bn7/ I have a watcher implemented on a computed property in my Vue component. This computed property depends on a Vuex store variable that is set asynchronously. Despite trying to update the data variable of the Vue comp ...

Issue with Typescript and react-create-app integration using Express

I'm relatively new to Typescript and I decided to kickstart a project using create-react-app. However, I encountered an issue while trying to connect my project to a server using express. After creating a folder named src/server/server.ts, React auto ...

Issue with transmitting Razor form data to API controller using fetch or AJAX

I have created a basic razor web project and defined it as follows: in program.cs I added builder.Services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN"); In the controller, this is what I did: [Route("/api/[controller]")] [ApiCon ...

Limit DerbyJS to re-rendering specific DOM elements

Currently, DerbyJS (visit http://derbyjs.com) functions by replacing everything in the body tag of the document each time a link is clicked. Is there a way to utilize the template, but replace only the content inside #main-content instead of refreshing th ...

What could be causing my jQuery script to not load properly on the first attempt?

I have a jQuery script set up on this particular webpage just before the ending body tag. Here is the script: <script> $(document).ready(function(){ var demomain = $(".demo-bg section"); var demomainW = demomain.height()+ 150 ...

How can I utilize JavaScript on the server-side similar to embedding it within HTML like PHP?

One aspect of PHP that I find both intriguing and frustrating is its ability to be embedded within HTML code. It offers the advantage of being able to visualize the flow of my code, but it can also result in messy and convoluted code that is challenging to ...

Guide on correctly accessing an attribute in AngularJS directive validators

Currently, I am working on a validator that validates dates in the format of MM/YYYY. However, I am struggling to figure out how to access an attribute every time the model changes: <input id="my-date" validate-short-date data-max-date="{ ...

Set up a timed event for a .js file to execute

I am currently exploring options for automatically running a JavaScript file multiple times per day, similar to Task Scheduler on Windows. Right now, I manually run the file in VS Code or Command Prompt using the command "node file.js". Is there a way to a ...

Firestore query failing to retrieve most recent data

I have implemented a route guard in Angular that validates a specific value in firestore before granting access to the designated route. The component is accessed only after an HTTP cloud function has finished executing. This cloud function generates an o ...

Utilizing client-side storage within a React project

As part of my React challenge tracking app development, I am looking to implement a feature where users can click on a challenge button, approve it, and then save the chosen challenge name to local storage. Later, this saved challenge will be displayed in ...

Toggle the visibility of a component in React by managing its state

Currently, I am faced with the challenge of toggling the visibility of a component based on a state value: import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; import Button from ' ...

Using Ajax with Laravel for Beginners

After clicking a button in my Laravel app, I want to update some data in the database using ajax without reloading the page. This is a simple ajax request where only a function in a controller needs to be invoked. I tried setting up the ajax request follo ...

Identify the Google Maps Marker currently displayed on the screen

Is there a way to generate a list of markers within the zoom range for Google Maps, similar to the functionality on this site I'm curious if I can achieve this using jQuery or if there is a built-in function for Google Maps v3? Thank you! ...

Changing the value of one particular key within an object during a reduce operation will impact all other keys within the object as well

I'm completely lost here. It seems like there's a reference issue causing all data properties to be overwritten with the value of the last row. I need help figuring out how to iterate over a list of objects, using specific keys to assign data to ...

PHP - Issue with AJAX Login Functionality

I have been developing an AJAX login system and encountering an issue where it does not send any response back unless I use exit("error here") in the script. However, my goal is to return a JSON response instead. The form structure: <div id="account" ...

How can I implement a loading spinner for my remote link_to in Rails 5 with turbolinks 5?

Despite the various questions on this topic, I have not found a solution that meets my needs. I am looking to display a custom spinner instead of Turbolinks' default progress bar when a link_to with remote:true is clicked. This action will replace par ...

The ng-token-auth plugin in combination with the ui-router resolver leads to a blank

I have been referring to the ng-token-auth documentation here in an attempt to implement a resolver for authentication using the validateUser function. However, when I add the code snippet provided in the documentation to my app.js file under the "home" st ...