Skip to content

Instantly share code, notes, and snippets.

@SuperstrongBE
Last active August 29, 2015 14:17
Show Gist options
  • Save SuperstrongBE/3ebb11c427f9bf4f9361 to your computer and use it in GitHub Desktop.
Save SuperstrongBE/3ebb11c427f9bf4f9361 to your computer and use it in GitHub Desktop.
Angular image parent cover directive
angular.module('MediasUtils',[])
/**
* @description An angular directive that resize media to cover his parent size.
*/
.directive('mediaCover',function (){
var linkFn
,layoutFn
;
/**
* Angular link function
* @param scope
* @param elm
* @param attrs
* @return void
*/
linkFn = function (scope,elm,attrs){
var $elm;
$elm = angular.element(elm);
if ($elm[0].tagName == 'IMG'){
$elm.on('load',function (){
layoutFn(angular.element(this));
})
}else {
layoutFn(elm);
}
};
/**
* Layout and resize the elm based on his parent width and height.
* @param elm
* @return void
*/
layoutFn = function (elm){
var parentW = elm.parent()[0].offsetWidth
,parentH = elm.parent()[0].offsetHeight
,mediaW= elm[0].offsetWidth
,mediaH = elm[0].offsetHeight
,sw = (parentW/mediaW)
,sh = (parentH/mediaH)
,s = Math.max (sw,sh)
,offsetW = (parentW - (mediaW*s))/2
,offsetH = (parentH -(mediaH*s))/2
;
elm.css({
marginLeft:offsetW+'px'
,marginTop:offsetH+'px'
,width:mediaW*s+'px'
,height:mediaH*s+'px'
})
};
return {
restrict:'A'
,link:linkFn
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment