这就是我的观点:
<body ng-controller="AdminCtrl">
<img ng-repeat="pic in pics" ng-src="{{pic}}" />
<form ng-submit="postPic()">
<input id="photos" type="file" accept="image/*" multiple/>
<button>Add Pics</button>
</form>
这是 Controller :
app.controller('AdminCtrl',['$scope', function($scope){
$scope.pics =[];
$scope.postPic = function() {
var files = $('#photos').get(0).files;
for (var i = 0, numFiles = files.length; i < numFiles; i++) {
var photoFile = files[i];
var reader = new FileReader();
reader.onloadend = function(e){
$scope.pics.push(e.target.result);
console.log($scope.pics);
};
reader.readAsDataURL(photoFile);
}
};
尽管我选择了许多文件并且它们也显示在控制台中(尽管是异步的),但我似乎无法根据 $scope.pics
的更新来更新 View 。 $scope.pics
不是被监视了吗?为什么会这样?
最佳答案
问题是您正在异步更改 $scope 对象,因此 Angular 不知道它需要处理的更改。 Angular 不会一直“观察”你的 $scope 对象。您通常不必显式使用 $scope.$apply()
的原因是,如果您在 Angular 生态系统中(即: Controller 构造函数),Angular 大多数时候会自动为您执行此操作, $scope 函数等)。
app.controller('AdminCtrl',['$scope', function($scope){
$scope.pics =[];
$scope.postPic = function() {
var files = $('#photos').get(0).files;
for (var i = 0, numFiles = files.length; i < numFiles; i++) {
var photoFile = files[i];
var reader = new FileReader();
reader.onloadend = function(e){
$scope.pics.push(e.target.result);
console.log($scope.pics);
$scope.$apply(); // force digest cycle
};
reader.readAsDataURL(photoFile);
}
};
这与 Angular 提供 $timeout
服务的原因相同,它只是 setTimeout
的包装器,但会自动为您触发一个摘要周期:https://stackoverflow.com/a/19609851/580487
TLDR;异步功能 [除了内置 Angular 东西] 不在 Angular 生态系统之外,因此您必须让 Angular 通过 $scope.$apply()
关于javascript - ng-repeat 不处理 FileReader,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30143095/