I would like to pick up a file with AngularJS:
HTML:
Following is my approach with a directive.
Directive
angular
.module('yourModule')
.directive('fileChange', function() {
return {
restrict: 'A',
scope: {
handler: '&'
},
link: function (scope, element) {
element.on('change', function (event) {
scope.$apply(function(){
scope.handler({files: event.target.files});
});
});
}
};
});
HTML
<input type="file" file-change handler="fileSelect(files)">
Controller
fileSelect = function (files) {
var file = files[0];
//you will get the file object here
}
Using Madura's answer from above, here's the complete flow for reading a local JSON file:
Create directive:
angular
.module('app.services')
.directive('fileChange', function() {
return {
restrict: 'A',
scope: {
handler: '&'
},
link: function (scope, element) {
element.on('change', function (event) {
scope.$apply(function(){
scope.handler({files: event.target.files});
});
});
}
};
});
HTML:
<input type="file" file-change handler="fileSelect(files)">
Javascript:
$scope.fileSelect = function(files) {
var file = files[0];
var reader = new FileReader();
reader.onload = function(e) {
console.log("on load", e.target.result);
}
reader.readAsText(file);
}