Skip to content

Instantly share code, notes, and snippets.

@locnguyen
Created March 14, 2014 01:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save locnguyen/9540442 to your computer and use it in GitHub Desktop.
Save locnguyen/9540442 to your computer and use it in GitHub Desktop.
AngularJS directive for drag and drop file uploading
'use strict';
(function () {
angular.module('ui').directive('imageDrop', function () {
return {
restrict: 'EA',
scope: {
dropFn: '&'
},
link: function (scope, element, attrs) {
element.bind('dragover', function (e) {
stopExecution(e);
});
element.bind('dragleave', function (e) {
stopExecution(e);
});
element.bind('drop', function (e) {
stopExecution(e);
e.dataTransfer = e.originalEvent.dataTransfer;
var file = e.dataTransfer.files[0],
reader = new FileReader();
reader.onload = function (event) {
element.attr('style', 'background: url(' + event.target.result + ') no-repeat top center;background-size: 100%;');
scope.$apply(function() {
scope.dropFn({ encodedImage: event.target.result, filename: file.name });
});
};
reader.readAsDataURL(file);
});
function stopExecution (e) {
e.preventDefault();
e.stopPropagation();
}
}
}
})
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment