Ammar Khan
Ammar Khan

Reputation: 2585

How to reload the background image with the same url inside directive

I want to reload the background image for a div with the same url inside directive. When my view load, I used this directive to show the image as a background to a 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);

        }
    });

My html element looks 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>

It works fine, but what happens I give a user to re-upload his profile image, so after it uploads, I want to refresh the background image with the same url. How can I make it happen? The above code not seems to be working.

Upvotes: 1

Views: 1101

Answers (1)

PSL
PSL

Reputation: 123739

Your issue most possibly is because of spaces in the random string (due to (new Date()).toString()) that you are appending to get the refreshed image from the browser. Spaces mean that you generate a bad image url, so you probably want to wrap url in quotes or use ticks.

Try changing it to:-

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

Or just get the ticks and append it.

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

Upvotes: 1

Related Questions