AngularJS更新范围$http承诺



我正在构建一个应用程序,该应用程序可以解析Excel文件浏览器端,然后将数据发布到Node。这一切都运行良好,但是当范围是时,我无法更新文件上传列表。

$scope.upload = function() {
    var files = document.getElementById('upload').files;
    var i, f;
    for (i = 0, f = files[i]; i != files.length; ++i) {
        var reader = new FileReader();
        reader.onload = function (e) {
            var data = e.target.result;
            var workbook = XLSX.read(data, {type: 'binary'});
            workbook.SheetNames.forEach(function(sheetName) {
                var sheetData = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);
                if(sheetData.length > 0){
                    Sheet.create(f.name, sheetName, sheetData).success(function(sheet){
                        $scope.sheets.push(sheet);
                        console.log($scope.sheets);
                    });
                }
            });
        };
        reader.readAsBinaryString(f);
    }
}

"Sheet"是工作表服务,create 方法返回$http请求的结果。正确的工作表列表(包括新工作表)将记录到控制台,但 UI 不会更新。

<div class="drive-item" ng-repeat="sheet in sheets | filter:query " >...</div>
尝试在

超时时包装更新代码。您收到 rootscope.inprogress 错误的原因是,当您调用 scope.$apply 时,摘要正在运行。因此,注入$timeout(您放置$scope的位置),然后

// model updating code in async block
// ...
// end model updating code
$timeout(); // triggers digest safely

if (!$scope.$$phase) { // check if we are in digest
    $scope.$digest(); // run digest
}

还将安全地调用摘要

最新更新