Angular element for dynamic background image based on conditions

I am searching for a directive that can automatically set the background image to a specific image if it exists, or default to another image.

The url is generated using the form /images/cards/card{{$index}}.jpg within an ng-repeat, however, not all images actually exist.

Currently, I have code that accomplishes this task, but it also logs failed $http requests to the console, which is not desired as the purpose of this script is to handle non-existent images gracefully. Are there any suggestions on how to prevent these error messages from being displayed? (I have considered using the error event available in an <img> tag, but cannot find evidence that background-image has a similar feature).

angular.module("stickers")
.directive('bkgDiv', function($http) {
    return {
        scope: {
            url: '@'
        },
        link: function(scope, elem, attrs) {
            // console.log("bkgDiv", scope.url);
            $http.get(scope.url)
            .success(function() {
                elem.css({backgroundImage: "url("+scope.url+")"});
            })
            .error(function() {
                elem.css({backgroundImage: "url(/images/animal.png)"});
            })
        }
    }
});

Answer №1

Within your controller, you could create an additional property alongside the image URL and check for its presence before assigning the result to a Boolean variable (taking into account how JS handles Booleans). This would allow you to utilize this new Boolean in your view.

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

Building collapsible table cell components using ReactJS and Bootstrap 4

For each table row, I need to implement a feature that allows users to click on it and view specific information related to that row. After doing some research, I came across this thread: Twitter Bootstrap Use collapse.js on table cells [Almost Done] I ma ...

Is there a way to track and observe the vertical movement of an element within a directive's link function?

Can you help me figure out the best way to $watch or bind the height position of an element? I have a scenario where I display three divs, one at a time in different tabs (using bootstrap). Each div has a different height, and my directive comes after thes ...

Why does Angular's $compile outputted link-function return the error "undefined is not a function"?

I'm currently working on developing an Angular directive that can split a given set of elements into a specified number of columns. I plan to utilize the content of this directive as a template for each individual item. My testing environment can ...

Swap a jQuery class with another if the class for ul li is currently active

I am currently developing a form builder and I would like to customize the appearance, specifically changing the color of the text. I want the text to be white when the class is set to active, and black when the class is not active. Is there a way to achi ...

Developing MCRYPT_RIJNDAEL_128 from scratch in Node.js

Attempting to replicate the php encryption script below using node.js: $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB); $iv = mcrypt_create_iv($size, MCRYPT_RAND); $msg = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, 'MY_KEY_LONG ...

Creating a flexible route path with additional query parameters

I am facing a challenge in creating a unique URL, similar to this format: http://localhost:3000/boarding-school/delhi-ncr However, when using router.push(), the dynamic URL is being duplicated like so: http://localhost:3000/boarding-school/boarding-school ...

Router failing to progress to subsequent page despite alterations in URL

In my react application, I have 3 pages: a login page, a homepage, and a video page. The issue is that when the login button is clicked, it successfully makes a POST request but does not navigate to the next page. Although the URL changes to the required ...

An unexpected error occurred: [$injector:modulerr] (unidentified)

My website is running smoothly with AngularJS on one page, but I'm encountering an error in the console on other pages that do not use AngularJS. The error message reads: Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.3.13/$in ...

Binding hover and load events using jQuery on elements that are dynamically generated

One should note that the click event can be successfully bound to an element with the class name keybox, even if this element is dynamically generated. The code for this would look like: $('body').on('click', '.keybox', funct ...

What is the process for converting this Greasemonkey code to JavaScript specifically for Android devices?

Having trouble loading a page and running a JavaScript code on it? Don't worry, you're not alone. I came across a Greasemonkey script that does the trick, but now I'm struggling to make it work on Android. It's probably because of my la ...

Exploring the functionalities of HTML5 mode in Angular and the HAL browser

I am in the process of implementing html5 mode within an AngularJS application. I need to configure the server to redirect all requests without a suffix (meaning without an extension, not static resources) to the base URL: @RequestMapping(value = "/{path: ...

Creating an event on the containing element

Here is my HTML tag: <ul> <li> <form>...</form> <div> <div class="A"></div> <div class="B"><img class="wantToShow"></div> </div> ...

Can one conceal the JavaScript code that has been written?

Can JavaScript (jQuery) codes be hidden from view? I have a program with several load() functions and I'm worried that everyone can see the page addresses. Is this a risk? Example code snippet: load('account/module/message/index.php'); ...

What is the best way to avoid duplicating this JQM function multiple times and instead reuse it efficiently?

After coming across this interactive demo, I successfully implemented it on my website using JQM. However, in order to activate the panel swipe feature, I had to include the following function: $( document ).on( "pagecreate", "#demo-page", function() { ...

Is there a way to automatically fill up a second dropdown menu based on the user's selection from the first dropdown

Using jQuery or vanilla JavaScript, I am looking to dynamically populate a second dropdown based on the selection made in the first dropdown. The value chosen in the first dropdown will determine which options are displayed in the second dropdown. What is ...

When the JSON object is transferred to the node server, it undergoes modifications

With the following code snippet, I have managed to develop a function that generates JSON data and transmits it to server.js (my node server). function deleteEmail(i) { emailObj.splice(i, 1); var general = {}; var table = [] general.table ...

mention a Vue.js component computed property that points to a specific DOM element

Is there a way to access the DOM element that initiated a method inside a Vue component computed property? For example: <template> <img :src="getUrl" class="image1"/> <img :src="getUrl" class="image2"/> </template> <scri ...

Strange Phenomenon in Node/Express.js: Vanishing Array Elements

My goal is to extract information from a database and store it in an array for further processing. However, I am facing an issue where the elements disappear after being added in a for-loop, resulting in an empty array. // PROBLEM: all_prices-elements dis ...

Develop a schema for an array of arrays in NodeJS using mongoose

Looking to establish a database schema for storing the following data: { name : "xyz", admin : "admin", expense : [ jan: [{expenseObject},{expenseObject}], feb: [[{expenseO ...

Utilizing various Firestore requests at varying intervals using the useEffect hook in React

useEffect(async() => { await getWord(); const interval = setInterval(() =>{ time2 = time2 - 1; if (time2 == 0) { clearInterval(interval); let dataURL = canvasRef.current.toDataURL(); const db = firebase.firestore(); ...