gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 04:40:04 27 4
gpt4 key购买 nike

我试图使用 angularjs 将文件转换为字节数组。它工作正常,还将字节代码和文件名添加到数组($scope.FileAttachments)中,当将其添加到 $scope.FileAttachments 时,客户端 ng-repet 将显示附加文件。文件转换完成,文件添加到 $scope.FileAttachments 也完成,但 ng-repeat 无法在正确的时间工作。有趣的问题是,当 View 内发生任何其他事件时,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 Controller 代码

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

最佳答案

是的,明白了,在 Controller 范围之外时需要使用 $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);
});
}

关于javascript - Angular $scope 与文件输入类型冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43862191/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com