Switching Between Background Images in Angular

Looking to change the background-image of an element upon clicking it.

Currently, this is what's in place:

<div class="item-center text-center" toggle-class="active cable"> 
  <div class="quiz-background"></div>
  <p class="size1 quiz-text">Cable</p>
</div>

CSS:

.quiz-background {
  width: 80%;
  min-height: 100px;
  background-image: url(images/ofertas/Cable_darkBlue.png);
  background-position: center center;
  background-size: cover;
  background-repeat: no-repeat;
  margin: auto;
  top: 20px;
  position: relative;
}

.cable .quiz-background {
  background-image: url(images/ofertas/Cable_lightBlue.png);
}

Toggle-class directive:

'use strict';

angular.module('libertyprApp')
.directive('toggleClass', function() {
  return {
    restrict: 'EA',
    link: function(scope, elem, attrs) {
      elem.bind('click', function() {
        elem.toggleClass(attrs.toggleClass);
      });
    }
  }
});

At present, the background image toggles with the class swap. However, the goal is to achieve this through inline styling

style="background-image: url(...)"
and have control over that particular inline background style.

Any suggestions for accomplishing this using Angular?

Thank you!

EDIT

This is what has been implemented so far, which seems to be working but unsure if it's optimal:

<div class="item-center text-center circle-image-quiz" toggle-class="active cable"> 
  <div class="quiz-background" style="background-image: url(images/ofertas/Cable_darkBlue.png);"></div>
  <p class="size1 quiz-text">Cable</p>
</div>

and CSS:

.quiz-background {
  width: 80%;
  min-height: 100px;
  background-position: center center;
  background-size: cover;
  background-repeat: no-repeat;
  margin: auto;
  top: 20px;
  position: relative;
}

.cable .quiz-background {
  background-image: url(images/ofertas/Cable_white.png)!important;
}

This approach involves toggling the class with the background image taking precedence over the inline styled one.

Adopting this method as there will be multiple elements requiring different background images on click and not clicked states.

Answer №1

In your controller, consider creating a variable called $scope.isActive. Utilize the ng-class directive to alter the background by toggling classes dynamically. Depending on a button click event, update the value of isActive to either true or false.

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

SignalR 2.2 users are experiencing a lack of message reception

I have developed a unique self-hosted SignalR application that is operating within the framework of a console application. To access the hubs within this application, I have implemented a wrapper class to avoid referencing the SignalR.Core assemblies direc ...

Is the background image viewport centered?

I am embarking on a new venture with a website design that is unfamiliar to me, but I have a clear goal in mind... My design concept involves a single large image measuring 1000px x 1000px as the background, while the actual content fills up only 500px x ...

What is the best way to extract the modal into its own file?

Greetings, fellow React developer who is new to the field! I have successfully implemented a React Class Component that includes a popup Modal. This Modal displays when a user clicks on an Item Card: import React from 'react'; import { Card, Bu ...

Implementing a 10-second alert display in selenium

Task at Hand: I need to display the alert on my page for a few seconds to allow reading. Is there any function in Selenium Web-driver that can help with this? I am new to automation and have been learning about explicit waits. I tried using explicit wait ...

Having trouble retrieving the default selected value from a drop-down list using angular.js

I am having trouble retrieving the default value of my dropdown list using angular.js. Below is an explanation of my code: <th> <select style="width:100%; border:none; font-weight:bold;" ng-options="sub.name for sub in noCourse track by sub.v ...

Changing the text of a button using ngClass in Angular's toggle functionality

Is there a way to modify the text of a toggled button class in Angular using Bootstrap? Currently, I have this code to toggle the class: html <!-- toggle button --> <button type="button" class="btn btn-primary mt-3 ml-3" (click)="status=!status ...

Refreshing a jsp page without the need to reload the content

On my jsp page, I am displaying the contents of a constantly changing table. This means that users have to refresh the page every time they want to see updated information. Is there a way for me to update the content dynamically without requiring users t ...

The sidebar navigation is not appearing on Safari and IOS devices

I am facing an issue with my fixed position navbar and sidebar menu buttons on mobile, specifically on IOS and Safari. When clicking on the cart or account buttons, the sidebar menu does not show up. It seems to be a compatibility issue, and I am looking f ...

Tips for efficient navigation through posts when they are loaded via a JSON file

Check out my Plnkr demo: http://plnkr.co/edit/brWn6r4UvLnNY5gcFF2X?p=preview Let's say I have a JSON file: { "info": { "test1": "test", "teste2": "test" }, "posts": [ { "name": "lorem ipsum", "content": "sit a ...

Holding off on routing the pathName through the router until the next-page-transitions have been completed

In my current setup, I have two distinct elements at play. Using the code snippet below: className={router.pathname.startsWith("/pagename") ? "menu-active" : ""} I am able to apply the menu-active class to the pagename naviga ...

Ember.js: My fixtures array is getting cleared out based on the way it is being accessed

I have 2 different controllers in my application. The first one, KeywordsIndexController, is defined as follows: App.KeywordsIndexController = Em.ArrayController.extend({ contentBinding: "App.Keyword.FIXTURES" }); The second controller, KeywordsNew ...

In the Rails environment, it is important to verify that the data sent through $.post method in jQuery is correctly

I’m facing an issue with my jQuery script when trying to post data as shown below: $.post({ $('div#location_select').data('cities-path'), { location_string: $('input#city_name').val() }, }); Although this code work ...

Switching the visibility of multiple textareas from block to none

I am currently exploring ways to make one text area disappear while another one appears in its place. With limited knowledge of Javascript and just starting my journey into HTML and CSS, I am reaching out to the forum for assistance or guidance on the rig ...

Using Flask's post method with AngularJS

As a newcomer to using Flask, I've been attempting to create a function that handles a post request. However, I'm encountering an issue where the angular controller always returns an error or if there is no error, I am unable to access the data s ...

Plugin for controlling volume with a reverse slider functionality

I have been customizing the range slider plugin found at to work vertically instead of horizontally for a volume control. I have successfully arranged it to position the fill and handle in the correct reverse order. For instance, if the value is set to 7 ...

Display the chosen option in the console by using onChange() function; this is analogous to how onSelect()

I'm having trouble getting the value of a select element to log in the console. I managed to do this with an onSelect() method, but the onChange() method isn't returning anything. Here's what I tried with the onChange() method: <Form.Gr ...

"Troubleshooting the inconsistency of GraphQL resolver context functionality between Playground and the client in the official NextJS starter

Currently, I am making adjustments to my NextJS/Apollo application to enable SSG with GraphQL API routes. I have referenced this official NextJS starter example as a foundation for configuring the client. An issue arose in my application which led me to g ...

Effortless Numerical Calculation for Trio Input Fields

I am in the process of setting up three numeric input fields that will automatically calculate and display results on the side. I am struggling with this task as I am not familiar with using ajax. Can someone assist me in implementing this functionality us ...

"Creating varying lengths of time with useSpring: A Step-by-Step Guide

Is there a way for my component to have an animation that fully displays in 0.3s when my mouse enters, but disappears in 0.1s when my mouse leaves? Currently, with useSpring, I can only define one duration for both scenarios. How can I set different dura ...

Sending an array of objects over socket io: A step-by-step guide

Recently, I've been struggling with an issue when trying to send an array of objects through socket io. This is my server-side code: var addEntity = function(ent) { entityBag.push(ent); }; var entityBag = []; addEntity(new Circle({ ...