background default image if ng-style image loaded is invalid url

前端 未结 2 1798
粉色の甜心
粉色の甜心 2021-01-05 20:46

I am adding background images to my div like this

ng-style=\"{\'background-image\' : \'url(\'+ myvariable.for.image +\')\'}\">

where myv

2条回答
  •  长情又很酷
    2021-01-05 21:47

    Instead of ngStyle I'd use a custom directive for this. Such as the following. This checks to see if an attribute is provided, if so it attempts to load that image. If it loads an image then we set the background image to it, otherwise we use a default image.

    myApp.directive('bgImage', function () {
        return {
            link: function(scope, element, attr) {
    
                attr.$observe('bgImage', function() {           
                  if (!attr.bgImage) {
                     // No attribute specified, so use default
                     element.css("background-image","url("+scope.defaultImage+")");
                  } else {
                     var image = new Image();  
                     image.src = attr.bgImage;
                     image.onload = function() { 
                        //Image loaded- set the background image to it
                        element.css("background-image","url("+attr.bgImage+")");
                     };
                     image.onerror = function() {
                        //Image failed to load- use default
                        element.css("background-image","url("+scope.defaultImage+")");
                     };
                 }
             });
          }
        };
    });
    

    Used like this:

     

    demo fiddle

提交回复
热议问题