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

Tips for utilizing ng-checked and ng-disabled in conjunction with ng-repeat

I encountered a challenge with ng-repeat while incorporating ng-checked and ng-disable alongside it. <div ng-repeat="module in modulelist"> <input id="switch{{$index}}" ng-init="setState($index);" type="checkbox" ng-checked="switch.checked" ng-di ...

Manipulating data with Angular's array object

I am having an issue with posting an object array. I anticipate the post to be in JSON format like this: {"campaign":"ben", "slots":[ { "base_image": "base64 code here" } ] } However, when I attempt to post ...

How come I can't see this on my display?

I'm facing an issue with this particular HTML snippet not displaying when I view the file in Chrome or any other browser. Below is the code: <!DOCTYPE html> <html> <head> <title> # <title& ...

Angular login/signup modal/dialog component for seamless user authentication

Currently, I am working on adding a login/signin dialog to my app similar to the one used by Medium. After doing extensive research online, I have decided to use the $modal from angular ui-bootstrap for this. Can anyone please recommend a tutorial that wil ...

The issue of the highlighted row not disappearing persists even after clicking on the adjacent table row

When selecting the gear icon for the menu option in a table row, I would like the background to turn yellow. I attempted the following code to highlight the table row: var view = Core.view.Menu.create({ model: model, menuContext: { ibmm: ibmm }, ...

how to style a page with a CSS arrow shape

Can someone help me figure out how to create an arrow similar to the one in this button using CSS? I've been able to create triangle-like arrows like the one below #triangle_arrow { top: 3pt; content: ""; display: inline-block; wid ...

Could Google Adsense be causing issues with my website's navigation bar?

There seems to be an irritating bug that I've come across. While navigating my website, [the menu (located in the top right corner) functions correctly]. However, when you land on a page with a Google AdSense ad, the menu suddenly appears distorted ...

I must click the web icon in order to open the link with buttons

I am having trouble with the buttons I added for my social media links. When I click on the button, it doesn't direct me to the link unless I click on the icon within the button. <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7. ...

Creating a personalized <select> filter in Angular.js with two different JSON choices

I am working with a Q&A JSON feed that includes the following: "questions": [ { "answer": "Ea et non sunt dolore nulla commodo esse laborum ipsum minim non.", "id": 0, "poster": "Chelsea Vang", "question": "Ex ex elit cu ...

Customize Bootstrap 5: Changing the default color scheme

Currently, I am utilizing Bootstrap 5 (v5.2.1) along with a form on my website. I am attempting to customize the default styles for form validation. Specifically, I want to modify the colored 'tick' or 'check' icon that is displayed wh ...

What is the best way to have gulp monitor my sass file updates and generate a single css file?

I'm currently working on a project using ASP.NET MVC 5 framework and Visual Studio 2013. In order to automate the process of compiling my sass files and publishing them into a bundle.css file, I decided to utilize gulp. Here are the steps I took: I ...

The import component path in Angular 4/TypeScript is not being recognized, even though it appears to be valid and functional

I'm currently working on building a router component using Angular and TypeScript. Check out my project structure below: https://i.stack.imgur.com/h2Y9k.png Let's delve into the landingPageComponent. From the image, you can see that the path ...

Convert to cshtml and retrieve the logged-in user's identification

I'm completely new to using AngularJS. I recently developed a demo login app, but I'm facing an issue where the page doesn't render even when the login id and password are correct. Code: app.controller('MainCtrl', ['$scope&ap ...

What is the purpose of utilizing jQuery for retrieving CSS resources?

Upon reviewing the Chrome Dev Tools screenshot, I am puzzled by the fact that my CSS assets are being fetched by jQuery. The CSS sheet is included in the normal way, using a <link rel="stylesheet"> tag in the <head> section, while jQu ...

What is the best method to restrict the size of a div to match the dimensions of the

In my webpage, I have a menubar (div) that contains bookmarks. However, when too many bookmarks are added, the menu becomes too wide for the page size I prefer (1280, 720) and becomes scrollable, causing some bookmarks to be out of view. My goal is to ens ...

Generating the templateUrl dynamically with ui-router

Looking to dynamically generate a template URL using the ID from my ng-click. However, running into an error: Uncaught Error: [$injector:modulerr] Failed to instantiate module mean due to: TypeError: filename.indexOf is not a function Below is my rou ...

When scrolling down a webpage, the background color of the content does not stretch along with the page

I've created a webpage with a sticky header and footer, along with a scrollbar on the main content. However, I'm facing an issue where the background color of the content does not extend beyond the viewport when scrolling down. The text is visibl ...

I'm having trouble setting the margin to 0 in Bootstrap 4. I'm only using CSS for styling and JavaScript for

Currently in the process of setting up a grid layout for a webpage under development. Encountering an issue with the .container class, that is supposed to contain all my div elements, not having any margin. Managed to remove the margin on the left side usi ...

Using AngularJS, you can display repeated elements in a single textarea by utilizing

--> I want to be able to input data into a textarea using just one textarea element. --> The reason for this is so that when the data in MySQL is updated, I can type new data in the textarea while still keeping the existing data. I have tried using ...

Alter the appearance of the mouse cursor when hovering over input fields in HTML

I am working with a variety of HTML elements that can be moved via Drag'n'Drop. In order to indicate to the user where these elements can be dropped, I change the cursor's appearance using CSS classes applied through JavaScript. This method ...