1

当我使用FileReader读取上传的文件并显示其数据时,我发现 html 中的 rootScope 变量将在单击两次后更新。但是我确定第一次单击后代码已经执行,因为变量已经更新。

http://jsfiddle.net/f8Hee/1/

这是我在互联网上找到的用于使用 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>

4

1 回答 1

2

那是因为onloadend没有在角度摘要循环中运行,所以即使data更新了属性,与范围关联的手表也不会被处理。

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>

于 2015-10-09T07:39:40.363 回答