【发布时间】:2014-02-14 09:03:12
【问题描述】:
我已经实现了一个 filedrop 指令,它将文件放置在 ngModel 中。
<filedrop data-ng-model="file"></filedrop>
我在控制器中使用以下代码:
$scope.$watch('file', function(newVal, oldVal) {
if (newVal) {
var reader = new FileReader();
reader.onload = function(event) {
$scope.parseFile(newVal);
};
reader.readAsDataURL(newVal);
}
}, false);
在 $scope.parseFile 我实际上是在解析 XLSX:
$scope.parseFile = function(file) {
xlsxParser.parse(file).then(function(data) {
console.log("Number of columns", data.datasheet[1].length);
console.log("Number of rows", data.datasheet.length);
$scope.validationErrors = [];
$scope.brand = {
items: []
};
$scope.dataItems = [];
$scope.datasheetValidate(data.datasheet, $scope.brand);
$scope.datasheetData(data.datasheet, $scope.dataItems);
if ($scope.validationErrors.length == 0) $scope.validationErrors.push("Nice work, no validation errors");
//$scope.$apply(function(){});
}, function(err) {
console.log('error', err);
});
}
如你所见,我注释掉了正文中的//$scope.$apply(function(){});....
但是,我需要它来更新我的网页以使用范围更改(例如,显示 validationErrors)
我怎么需要$scope.$apply?
【问题讨论】:
-
如果
xlsxParser.parse(file).then不是角度承诺回调方法,我看到这种情况发生的唯一原因。 -
你说得对。它使用 jQuery 承诺。可能需要重写借来的代码或接受我必须明确调用 apply 的事实:-(
-
很好,将其添加为答案,以便可以将问题标记为已回答。
标签: javascript angularjs angularjs-directive angularjs-scope dom-events