Guide on how to refresh the background image using the identical URL within a directive

I am looking to refresh the background image of a div using the same URL within a directive. Upon loading my view, I utilized this directive to display the image as a background for the div.

app.directive('backImg', function () {
        var directive = {
            link: link,
            restrict: 'A'
        };
        return directive;

        function link(scope, element, attrs) {



            attrs.$observe('backImg',function(n,o){
                if(!n) return;


                element.css({
                  'background-image': 'url(' + n + ')',
                  'background-size': 'cover'
                });


            },true);

        }
    });

The HTML element is structured like this

<div data-ng-if="vm.user.user_id!==undefined" data-back-img="{{vm.serviceUrl}}/image/user/{{vm.user.user_id}}"
             class="user-img-div" style="width:100%; height:100%;"></div>

While it functions properly initially, when a user updates their profile image, I want to refresh the background image with the same URL. How can I achieve this? The current code doesn't appear to be effective.

Answer №1

The issue you are facing is most likely due to the presence of spaces in the random string (resulting from using (new Date()).toString()) that you are adding to fetch the updated image from the browser. These spaces can lead to generating an incorrect image URL, hence it would be advisable to either enclose the URL in quotes or use ticks.

You can try modifying it as follows:-

          element.css({
              'background-image': 'url("' + n + '")', //Enclose URL in quotes
              'background-size': 'cover'
            });

Alternatively, simply acquire the ticks and add them to the URL.

      var random = new Date().getTime(); 

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

Playing only audio and no video in an Android WebView using HTML5

I am currently facing a challenge with a webpage that includes an html5 video and css3 animations. While the web page functions perfectly on an android device's browser, I am experiencing laggy, glitchy, and jumpy animations when using hardware accele ...

Do we require Node JS for developing Angular JS applications? If so, what is the rationale behind it? And why is Node JS not needed in a production environment?

Do you need Node.js to develop an AngularJS application? If so, what is the reason for that requirement? I have come across some articles stating that Node.js is necessary when building an AngularJS app, however, it is not needed in production. I am puzzl ...

Is it possible to create a single CSS style class that can be used for various section tiles on a website?

I am currently working on a website that includes different section titles such as About, Projects, Contact, and more. To make these titles stand out against the background image, I have decided to fill them with white. The text color of the titles is dar ...

Enhancing the appearance of an Angular.js application

On the same page, there are two buttons - one for buying and one for selling. It appears that both buttons share the same HTML instance. This creates a problem when trying to style them individually using classes, ids, or other HTML-targeted selectors, as ...

Leveraging Angular's ng-repeat and ng-show allows for specific data extraction from JSON

Looking to showcase the title and description of three items from a carousel, with data sourced from a JSON file via a unique code. Wondering if utilizing ng-show to specify 'if this matches code01 then display the corresponding data for that item&apo ...

Customize the appearance of Woocommerce's blockUi feature with your

During an Ajax request, blockUI adds a style to the blocks of the checkout form and cart with "background: '#fff'". However, my entire website theme is black and I do not want the background color of the blocks to be white. Is there a way to remo ...

Tips for customizing the appearance of date circles and text in Vue V-Calendar.io

On v-calendar.io, there is a demo showcasing the correct display where the date "2018-01-01" has a red background and dark text: However, my display does not match that. I have included Vue.js and v-calendar through CDN, and the page is formatted in HTML ...

Utilize ng-bootstrap in an Angular CLI project by integrating it with npm commands

I've been attempting to set up a project using Angular CLI with ng-bootstrap, but I'm having trouble getting the style to work properly. Here are the exact steps I followed (as outlined in the get-started page): Create a new project using `ng n ...

Variations in CSS display across various browsers

I'm currently facing an issue while learning web development. The expected result only appears when I preview my website on an old version of Internet Explorer, but it doesn't show up correctly when opened on Firefox or Chrome. The code I have i ...

Showing the date in AngularJSAngularJS can be used to

I have a view set up in AngularJS and I'm attempting to show the current date in a formatted way. My initial thought was to use <span>{{Date.now() | date:'yyyy-MM-dd'}}</span> to display the current date. ...

The outline none property on the Material UI IconButton is malfunctioning

Attempting to style with CSS as shown in the following example: <CustomColorIconButton> <DeleteForeverIcon /> </CustomColorIconButton> const CustomColorIconButton = withStyles({ root: { color: "#ff8833", ...

Unlocking protection: Confirming password strength and security with password indicator and regular expressions for special characters in angular through directive

I have developed an app for password validation using an AngularJS directive. The requirements for the password include at least one special character, one capital letter, one number, and a minimum length of 8 characters. Additionally, I have included a pa ...

Integrate a scrollbar seamlessly while maintaining the website's responsiveness

I encountered an issue where I couldn't add a scrollbar while maintaining a responsive page layout. In order to include a scrollbar in my datatables, I found the code snippet: "scrollY": "200px" However, this code sets the table size to 200 pixels r ...

Are promises returned by all API functions in Protractor?

During my test run: browser.get('http://www.valid-site.com').then(function(msg){ console.log(msg); }); I was anticipating the output to be either 1 or true, signifying a successful operation since get() is supposed to return a promise with ...

"Responsive header design using Bootstrap for both desktop and mobile devices

Is there a way to create a header that adjusts its width based on the device viewing it, with maximum width for desktop and no padding for mobile? Here is an example of the code: <div class="row"> <div class="span12"> ...

No space left around the image's border

Whenever I apply a border to an image, it comes with a margin and the image itself receives white padding. How can I remove the margin from the border? This is how I currently have it: border: 1px solid gray; ...

Image Not Displayed on Page

I am facing an issue where I have a div class 'breadcam_bg' with an image url, but the image is not being displayed on the page even though the console detects the div. html <div class="bradcam_area breadcam_bg"> This div! & ...

A rightward sliding submenu that appears upon clicking a button

I have a vision of creating an admin control panel for my website, featuring a set of buttons. I envision that when one of the buttons is clicked, the corresponding sub-menu will appear alongside it. For instance, if "My Account" is selected, its sub-menu ...

What are the steps to generate a service instance?

I am working on a unique service: (angular .module('app.services', ['ngResource']) .factory('MyService', [ /******/ '$resource', function ($resource) { return $resource('myurl'); ...

Steps for designing an HTML table that expands and collapses partially

I am currently revamping an old "Top Screens" page by expanding the display from the top 30 to the top 100 in a basic html table format. However, I only want to show the top 20 on page load with an expand/collapse feature. While I have come across examples ...