Joe Urc
Joe Urc

Reputation: 487

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!

Upvotes: 0

Views: 1382

Answers (2)

radius
radius

Reputation: 159

If you aren't opposed to putting the file reference in your markup, then this will work:

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

Upvotes: 0

U r s u s
U r s u s

Reputation: 6968

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.

Upvotes: 1

Related Questions