【发布时间】: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,你让我开心,工作正常。把你的答案用代码写出来,我会把它标记为有用的答案。
标签: javascript angularjs