简体   繁体   中英

AngularJS - Image not Rendering in ng-template

Inside of my ng-template, I have an img tag which I am trying to apply a background image. Find the template below:

<script type="text/ng-template" id="myModalContent.html">
...
    <a style="margin-left: 20px;" href ="">
        <img id = "printIcon" style="width: 64px;height: 70px">
    </a>
...
</script>

I am applying the .png icon in my .css file:

#printIcon{
    background-image: url("../img/printingIcon.png");
    background-size: 64px 70px;
}

When the ng-template is opened in a modal dialog, a request for the image is made (which I see in the network tab) and is loaded properly, but is not applied to the DOM. Even inspecting the img tag has the background-image property as the printingIcon.png file and previews it correctly. Is there anything special that needs to be done to apply images to DOM with ng-template, or am I doing something incorrectly? Thanks!

A more "Angular way" to achieve what you want is using a directive to manipulate the DOM.

Something like this:

var app = angular.module('app',[]);
app.controller('ctrl', function($scope){
});

app.directive('backImg', function(){
    return function(scope, element, attrs){
        var url = attrs.backImg;
        element.css({
            'background-image': 'url(' + url +')',
            'background-size' : 'cover'
        });
    };
});

Check out the full Fiddle .

如果您不反对将文件引用放入您的标记中,那么它将起作用:

<img ng-style="{'background-image':'url(/img/printingIcon.png)'}" width="64" height="70">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM