app .directive('ngThumb', ['$window', function($window) { var helper = { support: !!($window.FileReader && $window.CanvasRenderingContext2D), isFile: function(item) { return angular.isObject(item) && item instanceof $window.File; }, isImage: function(file) { var type = '|' + file.type.slice(file.type.lastIndexOf('/') + 1) + '|'; return '|jpg|png|jpeg|bmp|gif|'.indexOf(type) !== -1; } }; return { restrict: 'A', template: '', link: function(scope, element, attributes) { if (!helper.support) return; scope.$watch(attributes.ngThumb, function() { var file = scope.$eval(attributes.ngThumb); if (!helper.isFile(file)) return; if (!helper.isImage(file)) return; var canvas = element.find('canvas'); var remove = element.find('span[data-role="remove"]'); remove.on('click', function() { if (attributes.ngRemove) scope.$eval(attributes.ngRemove); }); var reader = new FileReader(); reader.onload = onLoadFile; reader.readAsDataURL(file); function onLoadFile(event) { var img = new Image(); img.onload = onLoadImage; img.src = event.target.result; } function onLoadImage() { var width, height; if (attributes.ngWidth >= attributes.ngHeight && this.width > this.height) { width = attributes.ngWidth; height = (width / this.width) * this.height; } else { height = attributes.ngHeight; width = (height / this.height) * this.width; } canvas.attr({width: width, height: height}); canvas[0].getContext('2d').drawImage(this, 0, 0, width, height); } }); } }; }]);