当我使用FileReader读取上传的文件并显示其数据时,我发现 html 中的 rootScope 变量将在单击两次后更新。但是我确定第一次单击后代码已经执行,因为变量已经更新。
这是我在互联网上找到的用于使用 fileReader 的小提琴,它仍然对我有同样的问题。您需要单击[add]按钮两次{{ data }}将更新。
代码来自 > 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>