So I am having some struggle with the code below:
app.factory('sfAttachment', ['$http', '$q', '$window', '$rootScope', function($http, $q, $window, $rootScope) {
var attachment = {};
//Save to server function for attachments
attachment.save = function(base64value, document, index) {
/*Stripping the file type text in front of the base64
string, without this the file would show as corrupted */
var position = base64value.indexOf("base64,");
var matchWord = "base64,";
var base64valueClean = base64value.slice(position + matchWord.length, base64value.length);
//Setting payload to be saved in SF database.
var data = {
"Body": base64valueClean,
"ContentType": document.attachmentContentType,
"ParentId": document.id,
"Name": document.fileName
};
/*Get the {!URLFOR('/services/data/v26.0/sobjects/Attachment/')} value
cannot be processed on static ressource, hence the link to the window
global variable.*/
var url = $window.__url;
var method = 'POST';
var request = {
url: url,
method: method,
data: data,
headers: {
__XHR__: function() {
return function(xhr) {
xhr.upload.addEventListener("progress", function(event) {
$rootScope.text = event.loaded/event.total;
$rootScope.$apply();
console.log("uploaded " + ((event.loaded/event.total) * 100) + "%");
});
};
}
}
};
console.log(request);
//Promise type approach to Http request, allows easy handle of succes and failure
// Very useful for asynchronous calls.
var deferred = $q.defer();
//Performing http request to Server
$http(request).then(function(response) {
deferred.resolve(response);
console.log('File UPLOADED to SF!');
}, function(event) {
//Need to Improve error handling!!!
deferred.reject('The attachment could not be saved:' + event);
});
return deferred.promise;
}
This service purpose is to load an Attachment into Salesforce and it works great, but then I added a piece of code
headers: {
__XHR__: function() {
return function(xhr) {
xhr.upload.addEventListener("progress", function(event) {
$rootScope.text = event.loaded / event.total;
$rootScope.$apply();
console.log("uploaded " + ((event.loaded / event.total) * 100) + "%");
});
};
to track the progress of the upload and it successfully output to the console the percentage, what I am trying to achieve is pass the progress percentage to the controller calling this service, and I am struggling a bit with that considering I already have a promise in place, not really sure how to properly grab the text, here my attempt is with $rootscope.text
and setting up a watch in my controller and it works but is there a more elegant/proper way of doing it?
$rootScope.$watch('text', function(newValue, oldValue, scope) {
console.log($rootScope.text);
});