Skip to content

Instantly share code, notes, and snippets.

@nelyj
Created June 5, 2015 18:37
Show Gist options
  • Save nelyj/80081f598749d4abbe90 to your computer and use it in GitHub Desktop.
Save nelyj/80081f598749d4abbe90 to your computer and use it in GitHub Desktop.
fileUpload to base64 Directive
.directive('fileUploaded', function ($q) {
var slice = Array.prototype.slice;
return {
restrict: 'A',
require: '?ngModel',
link: function (scope, element, attrs, ngModel) {
ngModel.$render = function() {};
element.bind('change', function(e){
var element = e.target;
$q.all(slice.call(element.files, 0).map( readFile ))
.then(function(values){
if (element.multiple) ngModel.$setViewValue(values);
else ngModel.$setViewValue(values.length ? values[0] : null);
});
function readFile(file){
var deferred = $q.defer();
var reader = new FileReader();
reader.onload = function(e){
deferred.resolve(e.target.result);
};
reader.onerror = function(e){
deferred.reject(e);
};
reader.readAsDataURL(file);
return deferred.promise;
};
}); //change
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment