Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular.js data-bind background images using media queries

I have an Angular.js application with dynamically background images (should have data-binding for their URL). I also want to use css media queries in order to detect orientation/pixel density etc.

The only solution I found is using javascript to add URL to the background image, something like this:

myDiv.css({'background' : 'url('+ scope.objectData.poster +') no-repeat', 'background-size':'auto 100%'});

This way I have to pass all media queries logic to javascript, something like this. (My intention is to be able to serve different background image for each screen resolution / pixel density / orientation)

I am looking for a cleaner solution to use css media queries and still be able to data-bind my image sources.

tnx!

Yaniv

like image 498
Yaniv Efraim Avatar asked Oct 02 '22 22:10

Yaniv Efraim


1 Answers

This is just a starting point solving your problem.

You may use matchMedia: https://developer.mozilla.org/en-US/docs/Web/API/Window.matchMedia

if (window.matchMedia("(min-width: 400px)").matches) {
    $scope.poster = 'small.png';
} else {
    $scope.poster = 'big.png';
}

now you can use it in the html file:

<div class="moments-preview-image" 
    ng-style="{'background-image': 'url('+poster+ ')'}"> ... </div>

If your browser doesn't support this new API you may have a look on some interesting workarounds:

http://wicky.nillia.ms/enquire.js/

http://davidwalsh.name/device-state-detection-css-media-queries-javascript

like image 158
michael Avatar answered Oct 05 '22 12:10

michael