Skip to content

Instantly share code, notes, and snippets.

@danmartens
Last active August 29, 2015 13:58
Show Gist options
  • Save danmartens/10428355 to your computer and use it in GitHub Desktop.
Save danmartens/10428355 to your computer and use it in GitHub Desktop.
AngularJS Responsive Image Tag
/***
* Example:
*
* <span ui-image
* load-image="true"
* srcset="[
* [image.large_mobile, '650w 1x'],
* [image.large_mobile_2x, '650w 2x'],
* [image.large, '1x'],
* [image.large_2x, '2x']
* ]" />
***/
angular.module('ui', []).directive('uiImage', function() {
return {
restrict: 'A',
transclude: false,
replace: false,
template: '<img ng-src="{{imageSrc}}" />',
scope: {
srcset: '=',
loadImage: '='
},
link: function(scope, elem) {
var matchesWidth = function(w) {
return w && window.innerWidth <= w;
};
var matchesHeight = function(h) {
return h && window.innerHeight <= h;
};
var matchesPixelRatio = function(x) {
return x && window.devicePixelRatio <= x;
};
var matchesOptions = function(options) {
var value = null;
options = options.split(/\s+/);
return _.every(options, function(o) {
if ( value = /^(\d+)w$/.exec(o) ) {
return matchesWidth( parseInt(value[1], 10) );
} else if ( value = /^(\d+)w$/.exec(o) ) {
return matchesHeight( parseInt(value[1], 10) );
} else if ( value = /^(\d+)x$/.exec(o) ) {
return matchesPixelRatio( parseInt(value[1], 10) );
} else {
return false;
}
});
};
var beforeImageLoad = function() {
$(elem).addClass('loading');
};
var afterImageLoad = function() {
$(elem).removeClass('loading')
.addClass('loaded');
};
var updateSource = function() {
if ( scope.loadImage && _.isArray(scope.srcset) ) {
_.each(scope.srcset, function(set) {
if (matchesOptions(set[1])) {
if (scope.imageSrc !== set[0]) {
beforeImageLoad();
var img = new Image();
img.addEventListener('load', afterImageLoad, false);
scope.imageSrc = (img.src = set[0]);
}
return false;
}
});
}
};
scope.$watch('loadImage', updateSource);
$(window).resize(function() {
scope.$apply(updateSource);
});
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment