gpt4 book ai didi

javascript - 将工厂服务的结果应用到范围 Controller

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:47:24 26 4
gpt4 key购买 nike

我正在编写一个上传服务。到目前为止上传工作正常。但我想用 xhr 回调更新 Controller 的范围,以便显示相关信息和 UI。

我该怎么做?我认为工厂服务不适合与 Controller 特定的东西混在一起。

adminServices.factory('UploadService', [function() {
return {
beginUpload: function(files, options) {
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", this.onUploadProgress, false);
xhr.addEventListener("load", this.onUploadComplete, false);
xhr.addEventListener("error", this.onUploadFailed, false);
xhr.addEventListener("abort", this.onUploadCanceled, false);
},
onUploadProgress: function(progress) {
console.log("upload progress"); //HERE I CAN'T UPDATE the CONTROLLER's SCOPE
},
onUploadComplete: function(result) {
console.log("upload complete"); //NOR HERE
},


app.directive('fileUpload', function() {
return {
restrict: 'E',
scope: {},
template: '', //omitted for brevity
controller: function($scope, UploadService) {
$scope.upload = function() {
UploadService.beginUpload($scope.files, options);
};
//HERE I'D LIKE TO HAVE NOTIFICATIONS OF THE onXYZ methods...

最佳答案

尝试在工厂中执行以下操作:

adminServices.factory('UploadService', [function() {
//Create a UploadService Class

function UploadService (scope) { //Constructor. Receive scope.
//Set Class public properties
this.scope = scope;
this.xhr = new XMLHttpRequest();
//Write any initialisation code here. But reserve event handlers for the class user.
}

//Write the beginUpload function
UploadService.prototype.beginUpload = function (files, options) {
//Upload code goes here. Use this.xhr
}

//Write the onUploadProgress event handler function
UploadService.prototype.onUploadProgress = function (callback) {
var self = this;
this.xhr.upload.addEventListener("progress", function (event) {
//Here you got the event object.
self.scope.$apply(function(){
callback(event);//Execute callback passing through the event object.
//Since we want to update the controller, this must happen inside a scope.$apply function
});
}, false);
}

//Write other event handlers in the same way
//...

return UploadService;
}]);

现在,您可以在指令 Controller 中使用 UploadService 工厂,如下所示:

app.directive('fileUpload', function() {
return {
restrict: 'E',
scope: {},
template: '', //omitted for brevity
controller: function($scope, UploadService) {
//Create an UploadService object sending the current scope through the constructor.
var uploadService = new UploadService($scope);

//Add a progress event handler
uploadService.onUploadProgress(function(event){
//Update scope here.
if (event.lengthComputable) {
$scope.uploadProgress = event.loaded / event.total;
}
});

$scope.upload = function() {
uploadService.beginUpload($scope.files, options);
};

希望对您有所帮助。干杯:)

关于javascript - 将工厂服务的结果应用到范围 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20503033/

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