Angular 指令中的 JS $scope.$on 不影响作用域变量
Angular JS $scope.$on in a directive don't affect scope variable
我做了一个 XHR 上传 Angular 服务,我试图通过 $rootscope
广播上传进度
...
xhr.upload.onprogress=function (evt){
if (evt.lengthComputable) {
percentComplete = Math.round((evt.loaded / evt.total)*100);
console.log(percentComplete)
$rootScope.$broadcast('upload:progress', percentComplete);
}else{
$rootScope.$broadcast('upload:progress', 'not computable');
}
}
...
指令是
...
$scope.$on('upload:progress', function (event,data) {
console.log('progress ' + data)
$scope.progress = data
})
...
html 文件是:
<div ng-controller="uploadController">
<input class="selectFile" type="file" multiple ng-model="files" file-change></input>
<br><br>
Selected: {{ files.length }}
{{files}}
<br><br>
<a href="" ng-click="upload()">Start Upload</a>
-- {{progress}}
</div>
控制台正确写入两个日志(一个来自 xhr.upload.onprogress 另一个在 $scope.$on )但是 $scope.progress 没有改变....
怎么了?
谢谢!
由于它是一个异步调用,在 AngularJS 生命周期之外,您需要 运行 $scope.$apply
显式触发 $digest
,这将更新视图:
$scope.$apply(function () {
$scope.progress = data;
});
我做了一个 XHR 上传 Angular 服务,我试图通过 $rootscope
广播上传进度...
xhr.upload.onprogress=function (evt){
if (evt.lengthComputable) {
percentComplete = Math.round((evt.loaded / evt.total)*100);
console.log(percentComplete)
$rootScope.$broadcast('upload:progress', percentComplete);
}else{
$rootScope.$broadcast('upload:progress', 'not computable');
}
}
...
指令是
...
$scope.$on('upload:progress', function (event,data) {
console.log('progress ' + data)
$scope.progress = data
})
...
html 文件是:
<div ng-controller="uploadController">
<input class="selectFile" type="file" multiple ng-model="files" file-change></input>
<br><br>
Selected: {{ files.length }}
{{files}}
<br><br>
<a href="" ng-click="upload()">Start Upload</a>
-- {{progress}}
</div>
控制台正确写入两个日志(一个来自 xhr.upload.onprogress 另一个在 $scope.$on )但是 $scope.progress 没有改变....
怎么了?
谢谢!
由于它是一个异步调用,在 AngularJS 生命周期之外,您需要 运行 $scope.$apply
显式触发 $digest
,这将更新视图:
$scope.$apply(function () {
$scope.progress = data;
});