When I use FileReader to read an uploaded file and show its data, I have found that the rootScope variable in html will update after twice clicks. But I'm sure the code have been executed after the first click, because the variable have been updated.
This is the fiddle that I have found on internet for usage of fileReader, and it still have the same problem with me. You need click [add] button twice the {{ data }} will update.
The code comes from > File Upload using AngularJS
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
$scope.data = 'none';
$scope.add = function(){
var f = document.getElementById('file').files[0],
r = new FileReader();
r.onloadend = function(e){
$scope.data = e.target.result;
}
r.readAsBinaryString(f);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-controller="MyCtrl">
<input type="file" id="file" name="file"/>
<br>
<button ng-click="add()">Add</button>
<p>{{data}}</p>
</div>
That is because the onloadend
is not running within the angular digest loop, so even though the data
property is updated the watches associated with the scope is not processed.
var myApp = angular.module('myApp', []);
function MyCtrl($scope) {
$scope.data = 'none';
$scope.add = function() {
var f = document.getElementById('file').files[0],
r = new FileReader();
r.onloadend = function(e) {
$scope.data = e.target.result;
$scope.$apply();
}
r.readAsBinaryString(f);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="MyCtrl">
<input type="file" id="file" name="file" />
<br>
<button ng-click="add()">Add</button>
<p>{{data}}</p>
</div>
</div>