2017-05-09 51 views
1

我試圖使用angularjs將文件轉換爲字節數組。它的工作正常,還將字節代碼和文件名添加到數組($ scope.FileAttachments),以及何時將它添加到$ scope.FileAttachments客戶端,ng-repetition將顯示附加文件。文件轉換完成,文件添加到$ 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); 
    }); 
} 
+0

您正在向控制器範圍外的'$ scope.FileAttachments'添加新元素,您必須調用'$ scope。$ apply()'來更新範圍。 – Titus

+0

感謝@Titus你讓我的一天,工作正常。把你的答案與代碼我會標記爲有用的答案。 – sebu

+0

[Angular JS視圖未正確更新]的可能重複(http://stackoverflow.com/questions/14135216/angular-js-views-not-updating-properly) – Titus

回答

0

是,心動不如行動,需要使用$範圍。$適用()控制器的範圍之外時。

$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); 
     }); 
}