AngularJS - Static Background Image Directive

by dingen2010

HTML

<div ng-app="myApp">
    <div>
        <h2>Vanilla Image:</h2>
        <img src="http://images2.wikia.nocookie.net/__cb20110811172434/fallingskies/images/f/fd/Totoro_normal.gif" />
    </div>
    
    <div>
        <h2>Fill 200x100</h2>
        <div class="wide" my-background-image="http://images2.wikia.nocookie.net/__cb20110811172434/fallingskies/images/f/fd/Totoro_normal.gif"></div>
    </div>
    <div>
        <h2>Fill 100x200</h2>
        
        hier
        <div class="tall" my-background-image="http://images2.wikia.nocookie.net/__cb20110811172434/fallingskies/images/f/fd/Totoro_normal.gif"></div>
    </div>
</div>

CSS

div.wide {
    width: 200px;
    height: 100px;
    border: 1px solid orange;
}
div.tall {
    width: 100px;
    height: 200px;
    border: 1px solid orange;
}

JavaScript

angular.
    module('myApp', []).
    directive('myBackgroundImage', function () {
        return function (scope, element, attrs) {
            element.css({
                'background-image': 'url(' + attrs.myBackgroundImage + ')',
                    'background-size': 'cover',
                    'background-repeat': 'no-repeat',
                    'background-position': 'center center'
            });
        };
    });