Angular.js - 不要在进程中同步 $scope 的值

Angular.js - Don't sync $scope's value in process

我想在页面中显示进程状态。在开始流程之前,我将 $scope 的值设置为 true。所以必须在页面中显示loading,但是在进程的时候页面被锁定并且不显示loading

angular.module('testApp').controller('testCtrl', function($scope){
     $scope.impFile=function(){
         $scope.processStatus= false;
         reader.readAsText(target.files[0]);

         reader.onload = function (e) {
             // start process, that take about 10 seconds
         }
         reader.onloadend = function () {
            $scope.processStatus= false;
         }
     }
});

Html:

<i class="fa fa-spinner fa-spin" ng-show="processStatus"></i>
<span ng-hide="processStatus">uploaded</span>

我假设您使用的是 FileReader(您可以在此处查看文档:https://developer.mozilla.org/en-US/docs/Web/API/FileReader

所以您可以做的是在 reader 开始读取文件时将 $scope.processStatus 设置为 true:

reader.onloadstart = function() {
    $scope.processStatus = true;
}

然后当您的 reader 完成文件读取后,您可以使用 reader.onloadend 已有的功能。

如果您查看文档,reader.onload 仅在读取操作完成后发生。

注意,reader.onloadend 和 reader.onload 的区别在于 reader.onloadend 会触发成功或失败,而 reader.onload 会触发仅在成功时

我找到了解决方案。我在 reader.onloadend 函数中添加 $scope.$apply.

angular.module('testApp').controller('testCtrl', function($scope){
     $scope.impFile=function(){
         $scope.processStatus= false;
         reader.readAsText(target.files[0]);

         reader.onload = function (e) {
             // start process, that take about 10 seconds
         }
         reader.onloadend = function () {
            $scope.processStatus= false;
         }
         //This is solution
         reader.onloadend = function (e) {
            $scope.csvFile.uploadStatus = false;
            $scope.$apply();
         }
     }
});