Seeking assistance with a new challenge - working with files in JavaScript is uncharted territory for me. I have a directive with a template that includes an input file and upload button.
<input type="file" ng-file-select ng-model="files">
<button ng-click="onFileSelect()">Upload</button>
In the directive's controller, my code looks like this:
$scope.onFileSelect = function() {
reader = new FileReader();
reader.onload = function() {
$scope.file_contents = this.result;
};
reader.readAsArrayBuffer($scope.files[0]);
//debugger;
$scope.$watch('file_contents',function(file_contents) {
console.log(file_contents);
if (angular.isDefined(file_contents)) {
... lots of coding to handle file_contents ...
}
});
};
After selecting a file and clicking Upload, the console displays undefined for (file_contents) on the first click. It only shows a value after clicking the button a second time.
When I uncomment the debugger, $scope.file_contents has a value when checked.
So, it seems like file_contents takes some time to be set but the $watch doesn't detect it. Could there be a unique reason for this delay? Does $watch not work properly with FileReader objects?
Edit 1:
Following advice provided, here's an updated version of the code:
$scope.onFileSelect = function() {
reader = new FileReader();
reader.onload = function() {
file_contents = this.result;
upload_file($scope.files[0],file_contents);
};
reader.readAsArrayBuffer($scope.files[0]);
};
upload_file = function(file,file_contents) {
<performing operations related to file_contents>
};
Despite removing all $watches, why do $digest errors still occur? There are no interactions with $scope in upload_file. The error message only states:
Error: [$rootScope:inprog] $digest already in progress
http://errors.angularjs.org/1.3.0-beta.10/$rootScope/inprog?p0=%24digest
What might be causing this issue?