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

前端 未结 2 1791
粉色の甜心
粉色の甜心 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:38

    {{place.name}}

    Using a $timeout inside that custom directive worked for me.

    .directive
    (
        'errBgSrc',
        function($timeout)
        {
            return {
                link: function(scope, element, attrs) 
                {
                    $timeout
                    (
                        function()
                        {
                            if(window.getComputedStyle(document.getElementById(attrs.id)).backgroundImage=='none'||window.getComputedStyle(document.getElementById(attrs.id)).backgroundImage==null)
                            {
                                document.getElementById(attrs.id).style.backgroundImage='url('+attrs.errBgSrc+')';
                            }
                            else
                            {
                                var image = new Image();
                                var style=window.getComputedStyle(document.getElementById(attrs.id)).backgroundImage;
                                var url=style.slice(5,style.length-2);
                                image.src = url;
    
                                image.onerror = function()
                                {
                                    document.getElementById(attrs.id).style.backgroundImage='url('+attrs.errBgSrc+')';
                                };
                            }
                        },
                        500
                    );
    
                }
            }
        }
    )
    

提交回复
热议问题