I have seen examples that use directives to enable AngularJS to access the content or properties of a file (for example in Alex Such's fiddle and blog post) but I would have thought the following simple code would work (it doesn't).
HTML:
<body ng-app="myapp">
<div id="ContainingDiv" ng-controller="MainController as ctrl">
<input id="uploadInput" type="file" name="myFiles" onchange="grabFileContent()" />
<br />
{{ ctrl.content }}
</div>
</body>
JavaScript:
var myapp = angular.module('myapp', []);
myapp.controller('MainController', function () {
this.content = "[Waiting for File]";
this.showFileContent = function(fileContent){
this.content = fileContent;
};
});
var grabFileContent = function() {
var files = document.getElementById("uploadInput").files;
if (files && files.length > 0) {
var fileReader = new FileReader();
fileReader.addEventListener("load", function(event) {
var controller = angular.element(document.getElementById('ContainingDiv')).scope().ctrl;
controller.showFileContent(event.target.result);
});
fileReader.readAsText(files[0]);
}
};
If I place a breakpoint on the line this.content = fileContent
I can see that the value of content
changes from "[Waiting for File]" and is replaced by the content of the chosen txt file (in my case "Hallo World"). A breakpoint on controller.showFileContent(event.target.result)
shows the same, the value changes from "[Waiting for File]" to "Hallo World".
But the HTML never re-renders, it stays as "[Waiting for File]". Why?
(N.B. I've put the code in a fiddle.)