Skip to content

Instantly share code, notes, and snippets.

@jonlil
Created June 17, 2014 12:08
Show Gist options
  • Save jonlil/c18e03ee3d4c212a0f5c to your computer and use it in GitHub Desktop.
Save jonlil/c18e03ee3d4c212a0f5c to your computer and use it in GitHub Desktop.
dropzone
'use strict';
angular.module('giveManagerApp')
.directive('dropzone', function ($http, $log) {
function upload(file, attrs) {
return $http.post(attrs.url || '/upload', file, {
headers: {
'content-type': undefined,
'X-File-Name': file.name,
'X-File-Size': file.size,
'X-File-Type': file.type
},
transformRequest: [
function (data) {
var fd = new FormData();
fd.append(attrs.fieldname || 'file', data);
return fd;
}
].concat(angular.identity)
});
}
return {
restrict: 'A',
transclude: false,
scope: {
allowedTypes: '=',
dropzone: '=',
success: '&',
error: '&'
},
link: function (scope, element, attrs) {
var cssActiveClass = 'highlight';
// default value
scope.dropzone = scope.dropzone || '';
// default handlers
var handleError = attrs.error ? scope.error : $log.error;
var handleSuccess = function(data) {
if(_.isArray(scope.dropzone)) {
scope.dropzone.push(data.data);
} else {
scope.dropzone = data.data;
}
};
if(attrs.success) {
handleSuccess = function(data) {
scope.success(data.data);
};
}
element[0].addEventListener('drop', function (event) {
$(this).removeClass(cssActiveClass);
event.stopPropagation();
event.preventDefault();
var dataTransfer = event.dataTransfer;
var url = dataTransfer.getData('URL'),
promise;
if(url === '') {
promise = upload(dataTransfer.files[0], attrs)
.then(handleSuccess)
.catch(handleError);
return promise;
} else {
throw new Error('Can\'t post link to image. Download it first.');
}
}, false);
element.on('dragenter dragstart dragend dragleave dragover drag drop', function (event) {
event.preventDefault();
});
element.on('dragstart dragover dragenter', function() {
$(element[0]).addClass(cssActiveClass);
});
element.on('dragleave dragend', function() {
$(element[0]).removeClass(cssActiveClass);
});
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment