angularjs: ng-src equivalent for background-image:url(...)


In angularjs you have the tag ng-src which has the purpose that you won't receive an error for an invalid url before angularjs gets to evaluate the variables placed in between {{ and }}.

The problem is that I use quite some DIV's with a background-image set to an url. I do this because of the excellent CSS3 property background-size which crops the image to the exact size of the DIV.

The only problem is that I receive a lot of errors for the exact same reason they created a ng-src tag: I have some variables in the url and the browser thinks the image doesn't exist.

I realize that there is a possibility of writing a crude {{"style='background-image:url(myVariableUrl)'"}}, but this seems 'dirty'.

I've searched a lot and can't find the right way to do this. My app is becoming a mess because of all of these errors.

This question is tagged with css angularjs

~ Asked on 2012-12-08 20:36:50

The Best Answer is


ngSrc is a native directive, so it seems you want a similar directive that modifies your div's background-image style.

You could write your own directive that does exactly what you want. For example

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

Which you would invoke like this

<div back-img="<some-image-url>" ></div>

JSFiddle with cute cats as a bonus:

~ Answered on 2012-12-08 21:51:12


This one works for me

<li ng-style="{'background-image':'url(/static/'+imgURL+')'}">...</li>

~ Answered on 2013-05-13 01:37:51

Most Viewed Questions: