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

angularjs, css

Solution

`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;
        element.css({
            '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: http://jsfiddle.net/jaimem/aSjwk/1/

Problem

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.

Original source

Related problems