When the initial image URL returns a 404 error, the ng-src path does not automatically switch to the alternative

I'm currently working on a webpage where I want to show an image only if the URL of that image is valid, using AngularJS.

The challenge I'm facing is that ngIf only checks whether a value is null or not. So, even if the URL returns a 404 error, something will be displayed. However, I want to display the image only if it exists and not if it returns a 404 error.

https://i.stack.imgur.com/WcC2T.png

Is there a way to prevent displaying the image if it returns a 404 error and only display it when it's available?

<img class="menu" ng-if="$ctrl.companyLogo" ng-src="{{ $ctrl.companyLogo}}">

JavaScript code:

$ctrl.companyLogo = "https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png"

Currently, instead of showing the default logo when companyLogo returns a 404 error, no image is displayed at all.

Answer №1

Utilizing the Image object allows you to verify if the image path returns a 404 error or an actual image.

var given_src = 'http://idontexist.com/404.png';
var image = new Image();
image.src = given_src;
image.onerror = function(){console.log('doesnt exist or something ');}
image.onload = function() {console.log('exists or something');};

Check out this fiddle https://jsfiddle.net/pLbdqf5d/, and keep in mind that $scope.$apply in the fiddle is a temporary solution; consider implementing a promise for this function 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

Verify Departure on External Links within Wordpress

Let me set the stage for you: We're dealing with a bank website here. So, whenever a user wants to click on an external link (could be to a Facebook page or a partner website), we need to have a notification box pop up saying "You are about to lea ...

Updating the default value of a MUI TextField: Step-by-step guide

I am in the final stages of completing my form, but I have encountered an issue when trying to display the current user's name in the defaultValue variable of the TextField from MUI. If the value starts as ""/null, or essentially empty, the ...

The function $.post(...) is failing to detect the JSON content in the

I am attempting to send a POST request to the server using the following code: var body = { PatientAgeFilter: { CompareOperator: parseInt(self.patientAge()), MoreThanVal: { AgeSpecifier: 0, AgeValue: parseInt(se ...

Locate the div in the array that includes ValueA, and save ValueB from it into a new variable

When the button is clicked, I retrieve the current value of a Select control using the following code... $('#myBtn').on('click', function (clickEvent) { var nameSelected = document.getElementById('mySelectControl').getEle ...

Generic partial application fails type checking when passing a varargs function argument

Here is a combinator I've developed that converts a function with multiple arguments into one that can be partially applied: type Tuple = any[]; const partial = <A extends Tuple, B extends Tuple, C> (f: (...args: (A & B)[]) => C, ...a ...

Passing data from a directive to a controller in AngularJS

Struggling to send a message from a directive to its parent controller, but it's not working. Here is the snippet of HTML: <div ng-controller="Ctrl"> <my-elem/> </div> This is the code in the controller that is supposed to list ...

A guide to toggling the check/uncheck status of a list box by clicking on a checkbox using

I am using a div and CSS id to control the checkbox check and uncheck functionality, but I am not getting the desired outcome from my source code Step 1: By default, the checkbox is unchecked and the listbox is disabled Step 2: When the checkbox is check ...

Error thrown: SyntaxError - Forbidden break statement in AJAX code execution

Trying to exit a loop nested within a statement has been a challenge. Despite researching similar questions on stackoverflow, I have not found a solution that works. Below is the current code in question: for (var i = 0; (i < 10); i++) { ...

What is the best way to include the existing query string value in the hyperlinks on my page?

My main coding objective is to simultaneously search multiple websites. To accomplish this, I want to create a query string containing the search terms (primarily for analytics purposes) using a form. By utilizing JavaScript, I am aiming to include the s ...

Using specific sections of JSON data to display in an alert message (Vanilla JavaScript)

I am seeking a bookmarklet that, upon clicking, will access JSON data and retrieve the "temp" information to display in an alert indicating the weather with just one click. Is there a method to achieve this or do I need to utilize a different API? Here&ap ...

The icon on my page is not displaying, and the responsive menu is also not appearing

After tweaking the @media {} settings, I noticed that the icon displays properly when reduced, but disappears completely when fully covered with {}. Additionally, my responsive menu is not visible as expected. `@import url('https://fonts.googleap ...

Exploring a JSON Object with nested properties, crafting changes, and producing a fresh object: A step-by-step guide

I am attempting to manipulate a JSON object with nested properties by replacing numeric values with computed values and returning a new object. The original object looks like this: var obj = { "a0": { "count": 41, "name": "Park", "new": { ...

Receiving Null Value Upon Asynchronous API Call Before Data Retrieval

Struggling with Fetching and Displaying API Data in a Table I am facing a challenge where I need to fetch an API multiple times and populate the data into a table. The issue arises when the data for a specific year is not available, causing the table to b ...

Retrieve the output of a function once the function has completed

I'm facing an issue where I need to wait for a function to return a value from my MySQL table before using it as a return for my const ProjektNameIntentHandler. Here is the relevant code snippet: const ProjektNameIntentHandler = { canHandle(handlerIn ...

Exploring the use of Rails and jQuery to automatically update data through the use of setTimeout and ajax calls

There's a specific page accessible in the browser at "/calendar" that directs to "calendar#index". Utilizing a javascript setTimeout function, I'm attempting to re-fetch and update data on my page using $.get ajax method. $.get("<%= calendar ...

"I'm encountering an issue with Passport.js where req.isAuthenticated is throwing an error as not

Recently I started working with node and express, along with passport.js for building an authentication feature. However, I encountered an issue while using a middleware function called "checkNotAuthenticated" in my routes. The error message I received was ...

Using Angular-Resource instances throughout the entire application

Within my code, I have set up a straightforward resource of categories that utilizes a cached query action: app.factory 'Category', ($resource) -> $resource "/categories/:id", {id: '@id'}, { query: { cache: true, isArray: true, ...

Uploading a file to a .NET Framework API Controller using React

I am trying to figure out how to send files in the request body to an API controller in .NET framework using React. My goal is to achieve this without changing the request headers, so I want to send it as application/json. What I am looking for is somethi ...

Ways to launch the React Material date picker while hiding the date input field

I am working with the react material (MUI-X) date picker and my specific requirement is to have the date picker open on button click without displaying the date text field. I simply want to show the calendar and allow users to select a date. I have explore ...

Execute various settimeout or display functions on various elements of a webpage

Just a heads up, I'm not really experienced in development. More on the newbie side of things, but eager to learn. I've been looking for an answer to my question, but so far haven't come across anything that fits my specific situation. It m ...