Angular $scope 与文件输入类型冲突

Posted

技术标签:

【中文标题】Angular $scope 与文件输入类型冲突【英文标题】:Angular $scope conflict with file input type 【发布时间】:2017-10-07 07:33:02 【问题描述】:

我试图使用 angularjs 将文件转换为字节数组。它工作正常,还将字节码和文件名添加到数组($scope.FileAttachments)中,当它被添加到 $scope.FileAttachments 客户端时,ng-repet 将显示附件。文件转换完成,文件添加到 $scope.FileAttachments 也完成了,但 ng-repeat 不能在正确的时间工作。有趣的问题是,当视图内发生任何其他事件时,ng-repeat 工作得很好。

HTML 代码

<input id="File1" ng-model="File1" onchange="angular.element(this).scope().file1Upload()" type="file" />

<table  class="table table-striped table-bordered table-list">
    <thead>
        <tr>
             <th>Name</th>
        </tr>
    </thead>
    <tbody id="tblAttachments">
         <tr ng-repeat="item in FileAttachments  track by $index">
             <td>item.AttachmentDescription</td>
          </tr>
    </tbody>
</table>

AngularJS 控制器的代码

$scope.FileAttachments = [];
var fileData;

function getBuffer(resolve) 
     var reader = new FileReader();
     reader.readAsArrayBuffer(fileData);
     reader.onload = function () 
          var arrayBuffer = reader.result
          var bytes = new Uint8Array(arrayBuffer);
          resolve(bytes);
     



$scope.file1Upload=function() 
     var files = document.getElementById("File1").files;
     fileData = new Blob([files[0]]);
     var promise = new Promise(getBuffer);
     promise.then(function (data) 
          $scope.FileAttachments.push(
              "AttachmentDescription": files[0].name.toString(),
              "FileValue": data.toString()
          );
     ).catch(function (err) 
          console.log('Error: ', err);
     );

【问题讨论】:

您在控制器范围之外向$scope.FileAttachments 添加新元素,您必须调用$scope.$apply() 来更新范围。 感谢@Titus,你让我开心,工作正常。把你的答案用代码写出来,我会把它标记为有用的答案。 Angular JS views not updating properly的可能重复 【参考方案1】:

是的,知道了,需要在控制器范围之外使用 $scope.$apply()。

$scope.file1Upload=function() 
      var files = document.getElementById("File1").files;
      fileData = new Blob([files[0]]);
      var promise = new Promise(getBuffer);
      promise.then(function (data) 
          $scope.$apply(function () 
              $scope.FileAttachments.push(
                   "AttachmentDescription": files[0].name.toString()
                   "FileValue": data.toString()
               );
          );
      ).catch(function (err) 
           console.log('Error: ', err);
      );
 

【讨论】:

以上是关于Angular $scope 与文件输入类型冲突的主要内容,如果未能解决你的问题,请参考以下文章

前端组件用 Scope 发布 npm 包的方法

Angular之作用域

Angular Scope解析与应用

在业力旁边使用玩笑的冲突类型,Angular 上的茉莉花

Angular.js 中 copy 赋值与 = 赋值 区别

Angular Controller $scope.fId 显示未定义的值