使用 ngRepeat 和 ng-src 时看不到要上传的图像预览

Can't see Preview of Image to Upload when using ngRepeat and ng-src

本文关键字:图像 ngRepeat ng-src 看不到 使用      更新时间:2023-09-26

我已经为我的问题创建了一个CodePen示例。

我正在使用HTML5 FileReader和Angular来创建一个简单的多文件上传,其中包含要上传的图像的预览。

问题:我没有在ng-repeat范围内获得选定的图像。 但是,当我将其注销到控制台时,我确实获得了正确的图像数据......我做错了什么?

.HTML:

<div class="container" ng-app="my.app" ng-controller="FileUploadController">
  <div class="row">
    <div class="page-header">
      <h3>File Upload Test</h3>
    </div>
    <input type="file" class="well" id="files" name="files[]" multiple onchange="angular.element(this).scope().upload()" />
    <span ng-repeat="x in images">
      <img ng-src="{{x}}" />
    </span>
  </div>
</div>

.CSS:

img {
  max-height: 100px;
}

Javascript:

var app = angular.module("my.app", []);
app.controller("FileUploadController", function($scope) {
  $scope.images = [];
  $scope.upload = function() {
    var files = document.getElementById("files").files;
    if (files) {
      for (i = 0; i < files.length; i++) {
        if (files[i]) {
          var reader = new FileReader();
          reader.onload = function (e) {
            console.log(e.target.result);
            $scope.images.push(e.target.result);
          }
          reader.readAsDataURL(files[i]);
        }
      }
    }
  }; 
})

http://jsfiddle.net/orion514/kkhxsgLu/136/具有相同的工作实现。

<div ng-repeat="x in images">
<img class="thumb" ng-src="{{x}}" />

$scope.images = [];
$scope.imageUpload = function(event){
     var files = event.target.files; //FileList object
     for (var i = 0; i < files.length; i++) {
         var file = files[i];
             var reader = new FileReader();
             reader.onload = $scope.imageIsLoaded; 
             reader.readAsDataURL(file);
     }
    $scope.imageIsLoaded = function(e){
        $scope.$apply(function() {
            $scope.images.push(e.target.result);
        });
    }
}

在修改集合时尝试$scope.$apply(),如下所示,

     reader.onload = function (e) {
        console.log(e.target.result);
        $scope.images.push(e.target.result);
        $scope.$apply();
      }