What is the best way to verify the existence of a remote image in AngularJS?

Here is an example of the code snippet :

<div ng-repeat="u in users">
<!--An active URL will always be received -->
<div ng-if="u.imageUrl"> <!--Check if the provided URL is active-->
 <!--Content only visible if image url is live and active -->
</div>
<div>
<!--Do other operations here-->
</div>
</div>

For instance:

http://www.pacinno.eu/wp-content/uploads/2014/05/placeholder1.png
is an active URL, while
http://www.pacinno.eu/wp-content/uploads/2014/05/placeholder11.png
is not. Also, keep in mind that the users object may contain multiple records as more people sign in.

Answer №1

To achieve this functionality, you can utilize a directive:

Check out the demo

JavaScript:

.directive('replaceImage', function() {
    return {
        link: function(scope, element, attrs) {
            var defaultImage = 'path/to/default/image.jpg';

            scope.$watch(function() {
                return attrs.url;
            }, function (value) {
                if (!value) {
                    element.attr('src', defaultImage);  
                }
            });

            element.bind('error', function() {
                element.attr('src', defaultImage);  
            });
        }
    };
});

HTML:

<div ng-repeat="item in items">
    <div>
      <img url="{{item.imageUrl}}" replace-image />
    </div>
<div>

Now, if the URL specified in the url attribute is invalid, it will display the default image instead.

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

Ways to retrieve the state from the Redux store

While working on setting up the Redux store in my app.js file, I found myself populating it with data from the database. However, now I am faced with the task of obtaining the state of the store in a plain JavaScript file, not a React class. If I was work ...

Refreshing specific iframes without having to reload the entire webpage using jQuery

As the page loads initially, a hidden iframe and other visible ones are present. When a button is clicked, one of the visible iframes needs to be hidden while another becomes visible (with its src attribute set accordingly). The goal is to achieve this wit ...

Exploring the world of jQuery AJAX alongside Google's currency calculator

I'm currently working on a code that utilizes an AJAX call to access the Google currency calculator. The expected outcome is to receive a JSON array that can then be used to gather exchange rate data. Here is the link: http://www.google.com/ig/cal ...

PHP file secured to only accept variables posted from HTML form

This is a basic HTML/AJAX/PHP script I have implemented. <form id="new_user" action="" method="post"> <div class="col-md-3 form-group"> <label for="username">Username</label> <input type="text" class="form-control" name ...

What is the best way to send a parameter to the callback function of a jQuery ajax request?

I am facing an issue where I need to pass additional variables to a jQuery ajax callback function. Consider the following scenario: while (K--) { $.get ( "BaseURL" + K, function (zData, K) {ProcessData (zData, K); } ); } func ...

Guide to displaying a particular item in Vue 3

Currently, I am embarking on a project that requires the functionality to print a specific element of my webpage. After some research, I came across a mixin/plugin known as VueHtmlToPaper which seems to be the perfect solution for what I need. However, I a ...

Setting state back to default following the conditional rendering of a React component

Whenever the save button is clicked, I aim to display a snackbar component by updating the showSnackbar state to true. To achieve this in React, it's just a simple conditional check in the main render method. The snackbar I'm using here automatic ...

Incorporating multiple colors into a div with jQuery: A guide

I am looking for a way to create a legend by merging a specified number of colors within a div. I came across this useful Sample code that I have referenced. $.each(Array(50), function() { $("<div>").appendTo(document.body); }); var divs = $(&a ...

Delaying navigation to the next URL until a distinct category name is identified

Within this section of JSP code, I am implementing JavaScript and AJAX to validate the uniqueness of a category name. When the submit button is pressed for the first time, it prompts the user to enter a category name. Subsequently, an AJAX call is made to ...

Select a random class from an array of classes in JavaScript

I have a collection of Classes: possibleEnemies: [ Slime, (currently only one available) ], I am trying to randomly pick one of them and assign it to a variable like this (all classes are derived from the Enemy class): this.enemy = new this.possibleEn ...

Issue with adding a key:value pair to res.locals.object in Node/Express not functioning as expected

Currently, I am working on constructing an object within res.locals by executing multiple MongoDB operations and utilizing the next() middleware. Once I have added an object to res.locals, such as: res.locals.newObject, my goal is to subsequently add addi ...

How does the 'snack bar message' get automatically assigned without being explicitly defined in the 'data' function?

As a novice in web development and Vue, I am currently engaged in a simple project using Vuetify with Vue.JS 3. Within one of my views, there is a table that triggers a message and fetches status to display a snackbar to the user: methods: { async fetc ...

Modify the key within an array of objects that share a common key

I have an object structured as follows: NewObjName: Object { OLDCOLUMNNAME1: "NEWCOLUMN_NAME1", OLDCOLUMNNAME2: "NEWCOLUMN_NAME2", OLDCOLUMNNAME3: "NEWCOLUMN_NAME3"} Next, there is an array containing objects in this format: ...

Node(Meteor) experiencing a memory leak due to setTimeout

I have encountered an unusual memory leak associated with the use of setTimeout. Every 15 seconds, I execute the following code using an async function that returns an array of promises (Promise.all). The code is supposed to run again 15 seconds after all ...

Troubleshooting issues with adding rows to an HTML table

I want to include two buttons at the top of my page: Save and Cancel. These buttons should only appear after clicking the Submit button on the Customer Information panel. However, when trying this, the Customer Information panel is pushed down while I al ...

Using python to scrape images from a website with AJAX using selenium and beautifulsoup

After spending a considerable amount of time delving into html, javascript, network traffic, and expanding my knowledge on javascript, blobs, and base64 encoding/decoding of images, I am still struggling to extract images from videos on a particular websit ...

Using JQuery's appendTo method with a lengthy string of elements that includes a mix of single and double quotes: a step-by-step guide

My content script is fetching data from the server in the form of an array of objects. The structure looks something like this: [ { "lang": "English", "videos": [ { "embed": "<iframe width='100%' height='421px&apo ...

Sometimes the data-autoplay feature does not function properly in jQueryfullPage.js

I am in the process of developing an HTML page using jQueryfullPage.js. Within this page, I have incorporated 17 videos across 17 different sections. These videos are presented as YouTube iframes with a data-autoplay attribute. Overall, everything is fun ...

How can I add a black-colored name and a red-colored star to the Placeholder Star as a required field?

I'm looking to customize the placeholder text in an input field. I want the main placeholder text to be in black and have a red star indicating it's a required field. However, my attempt to set the color of the star specifically to red using `::- ...

Generating a Personalized XML Format Using Information from a Single MySQL Table Row by Row

If anyone can assist with this, I would greatly appreciate it: <warehouse> <frontbay> </frontbay> <bayrow> <bay> </bay> <bay> ...