I've got a weird one (for me at least) that hopefully someone will be able to help with. Maybe I'm just thinking about this the wrong way or something. Attempting to work with files in javascript is completely new to me.
I've got a directive whose template looks like this:
<input type="file" ng-file-select ng-model="files">
<button ng-click="onFileSelect()">Upload</button>
In the controller for the directive, I am doing 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)) {
... bunch of code attempting to deal with file_contents ...
}
});
};
I choose a file, then click the Upload button. The console.log of (file_contents) is undefined. Only when I click the button the second time, does it have a value.
If I uncomment the debugger, $scope.file_contents has a value by the time I'm checking it.
So, file_contents takes a moment to get set (which is expected), but the $watch never seems to notice? Is there some strange reason for this? Does $watch not work with FileReader objects?
Edit 1:
Okay. Here's some more information. Following PSL's advice, I now have the code as such:
$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) {
<lots of cool file_contents-y stuff>
};
Why am I still getting $digest errors? I have no $watches any more. I don't do anything with $scope within upload_file. There's no stack trace from the $digest error to help me, either. All I get is:
Error: [$rootScope:inprog] $digest already in progress
http://errors.angularjs.org/1.3.0-beta.10/$rootScope/inprog?p0=%24digest
What's doing this?