Skip to content

Instantly share code, notes, and snippets.

@Geoffrey-T
Forked from GuillaumeJasmin/resizeImg.js
Last active December 30, 2015 20:39
Show Gist options
  • Save Geoffrey-T/7882196 to your computer and use it in GitHub Desktop.
Save Geoffrey-T/7882196 to your computer and use it in GitHub Desktop.
angular.module('myModule')
.directive('resizeImg', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var width = element.parent().width();
var maxHeight = attrs.height;
var newHeight, newWidth;
var img = new Image();
img.onload = function() {
if( (width / this.width ) > (maxHeight / this.height) ) {
newWidth = maxWidth;
newHeight = Math.round( (width * this.height) / this.width);
} else {
newHeight = maxHeight;
newWidth = Math.round( (maxHeight * this.width) / this.height);
}
element.parent().css({
'background-image': 'url(' + attrs.ngSrc + ')',
'background-size': newWidth + 'px ' + newHeight + 'px',
'width': '100%',
'height': maxHeight + 'px',
'display': 'block',
'background-position': 'center center',
'background-repeat': 'no-repeat'
});
element.css('display', 'none');
};
img.src = attrs.ngSrc;
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment