What is the best way to display a variable with a `new Image()` in an AngularJS ng-repeat loop?

I have an array filled with different Image objects:

var imageList = [ image1, image2, image3 ];

Each element in this array is a variable that holds new Image(). For instance: var image1 = new Image().

I use the .onload event to preload each image after setting its URL. Only once all images are loaded can other operations take place.

How can I display each element of the array in AngularJS and show the image?

<li ng-repeat="image in imageList">
   {{ image }}
   /* I want the output of the above line to appear like
      <img src="./img/xx.svg" /> */
</li>

I do not want to follow a method like the one below since each element in the array has already been created as a new Image():

<li ng-repeat="image in someImageList">
   <img ng-src="{{ image.url }}" />
</li>

If I try {{ image }}, the current output shows just {}. Using solely image results in a list containing "image" strings.

The rationale behind creating new image elements using JavaScript instead of <img/> tags is twofold: 1. The need for preloading images, and 2. The requirement to draw these images in <canvas>. Repeating the creation of <img/> for the same image sources would be redundant. Additionally, it would slow down the opening of a modal displaying a collection of these images. Therefore, by preloading the images beforehand, the modal potentially opens quicker.

Answer №1

To save the image, you must convert it to a data URI.

$scope.images = [];

loadImage('./img/xx.svg');

function loadImage(src) {
  var img = new Image();

  img.onload = function() {
    // Create a canvas
    var canvas = document.createElement('canvas');

    // Ensure the canvas matches the image size
    canvas.width = this.width;
    canvas.height = this.height;

    // Draw the image on the canvas
    canvas.getContext('2d').drawImage(this, 0, 0);

    // Add the data URI to your scope
    $scope.images.push(canvas.toDataURL('image/png'));

    // Update Angular about the change
    $scope.$apply();
  }

  img.src = src;
}

Then, you can display it as follows-

<li ng-repeat="image in images">
   <img ng-src="{{ image }}" />
</li>

The image will be in data URI format instead of a URL.

You have flexibility in implementing this using the canvas.

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

Missing HTTP request payload

Utilizing Groovy script for executing an HTTP POST request with specified data: import groovyx.net.http.HTTPBuilder import static groovyx.net.http.ContentType.* import groovyx.net.http.ContentType import static groovyx.net.http.Method.* def http = new HT ...

Angular 4 Modals - Enhancing User Experience

Seeking the most effective method to incorporate modals in Angular 4 while adhering to the component architecture. Multiple tutorials and external libraries have been explored, all with limited usage. The common approach involves creating a Modal Service ...

How to set a default checked value in a custom DropDownList in AngularJS?

I have created a bespoke DropDownList in my HTML code. I'm looking for guidance on how to set one of the options as default within the following scenario: <div class="dropdownlistheader" ng-click="toggle('subdiv','item')"> ...

Transfer the address information to the billing address fields

I need assistance with copying the user's address to the billing address fields based on a checkbox value. Currently, when the checkbox is checked, only the last input field value is being copied over to the billing address section. It is crucial that ...

Avian-themed masking feature for jCarousel

Currently, I have a series of images in constant motion using jCarousel. Only one image is visible fully at any given time, and I am looking to create a "feathering" effect on the edges of the carousel so that the images smoothly fade in and out as they co ...

Embedding WebGL into XML files

My goal is to manipulate my XML documents directly and display specific data/elements using WebGL. To accomplish this, I incorporate xhtml:script to execute my JavaScript code. Although the WebGL API is present (such as window.WebGLRenderingContext), I en ...

Bootstrap 3 and Angular UI.Bootstrap Accordion working together

Although I am aware that ui.bootstrap is not fully adapted to Bootstrap 3 yet, my app is mostly built using it and reverting back to version 2.3 just for this component is not an option. Therefore, I am currently exploring my options. Here's what I ...

Attempting to use Vue.js for playing MP3 files

Motive: My objective is to incorporate a background sound into my project using a local file that can be played and paused. While loading an external URL file works fine and allows for play/pause functionality, I am encountering issues with the local fil ...

Having trouble getting Calendly Webhooks to function in a node.js environment with ngrok?

Hello everyone, this is my first time seeking help on Stack Overflow so please bear with me if there are any flaws in my question. I recently started using the Calendly Teams version and decided to implement the Webhooks feature on a Node.js web applicati ...

Setting up the Webpack configuration for a React application to incorporate source maps from external React packages that are listed as dependencies

How can the webpack.config.js file generated by a default React app be modified to allow for debugging of *.jsx files from other React packages listed as dependencies? The goal is to leverage the source maps provided by dependencies in order to debug JSX ...

Error encountered with jQuery XML: 'Access-Control-Allow-Origin' header is not present on the requested resource

For a personal project I'm working on just for fun, I'm trying to read an XML file from , parse the data, and use it to convert currency values. Although my code to read the XML is quite basic, I encountered the following error: XMLHttpRequest ...

Ways to transform date into a different structure using JavaScript

Fetching a date from an API gives me this format: 2017-04-20T07:00:00Z How can I convert it to the following format? 20.04.2017 I am using React to render the date: <div>{props.data.day}</div> I attempted to use toISOString().slice(0, 1 ...

Utilizing Foundation JS for Responsive Design on Media Queries

Is it possible to utilize the JS functions in Foundation to detect Media Queries? I am specifically interested in defining functions that will only fire in Medium-up media queries. More precisely, I am looking for a way to trigger the Foundation Equalizer ...

What is the best way to choose all checkboxes identified by a two-dimensional array?

I need help with a question div setup that looks like this: <div class="Q"> <div id="Q1"><span>1. </span>Which of the following have the same meaning?</div> <div class="A"><input type="checkbox" id="Q1A1Correct" /& ...

getting the angular service to function correctly

After referencing this source, I am working on creating a new service in angular that will display messages based on user actions such as add, edit, update, delete. Here is the current implementation, meanApp.factory("flash", function($rootScope) { var ...

Using a Do/While loop in combination with the setTimeout function to create an infinite loop

Having trouble with this script. The opacity transition works fine, but there seems to be an issue with the loop causing it to run indefinitely. My goal is to change the z-index once the opacity reaches 0. HTML <div class="ribbon_services_body" id="ri ...

The entry description function is not functioning properly when used with jGFeed

I have implemented jGFeed to extract data from an RSS Feed. Below is a snippet of the code I am using: $.jGFeed('http://feeds.bbci.co.uk/news/rss.xml', function(feeds){ // Check for errors if(!feeds){ ...

Leveraging Ajax, jQuery, and localStorage for seamless cross-browser

I have implemented an Ajax jQuery function that saves the scroll position in a localStorage. It seems to be working perfectly fine on Chrome, but unfortunately, it is not functioning correctly on other web browsers. What steps can I take to ensure that thi ...

Retrieve the smallest value from an array of objects using BitGO

Bitgo stores all transactions as objects within a large array. Within the nested .entries, we can identify that the first TX object contains two negative values -312084680 and -4254539, of which I only require the lowest value. My current code successfully ...

Obtain the data from the hyperlink destination

Having some trouble extracting a value from an href link to use in my database operations. Unfortunately, I couldn't retrieve the desired value. Displayed below is the code for a button: <a class="btn btn-info" href="scheduleSetTime.php?id=&apo ...