Skip to content

Instantly share code, notes, and snippets.

@taher435
Created July 4, 2016 02:38
Show Gist options
  • Save taher435/9455a220ad82a1df35da457ec9f24282 to your computer and use it in GitHub Desktop.
Save taher435/9455a220ad82a1df35da457ec9f24282 to your computer and use it in GitHub Desktop.
//Directive for file upload
app.directive('fileUpload', function () {
return {
scope: false,
link: function (scope, el, attrs) {
el.bind('change', function (event) {
var files = event.target.files;
scope.$emit("fileUploaded", { file: event.target.files[0] }); //since we need only single file upload right now
});
}
};
});
{code}
//Listen for "fileUploaded" event in the controller.
//"fu" is the angular app object. Replace it with your own object. You would do something like this in your controller "var fu = this;"
$scope.$on("fileUploaded", function (event, args) {
$scope.$apply(function () {
var reader = new FileReader();
reader.onload = function(event){ //this function will be called when we read data (below line)
try{
fu.fileContent = event.target.result;
}catch(e){
console.log(e.message);
$scope.$apply(function(){
fu.fileName = null; //setting fileName to null will allow us to do validations
});
}
};
fu.file = args.file;
fc.fileName = args.file.name;
reader.readAsText(args.file); //we can skip this if reading data is not required
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment