How to add Angular $ http event listeners

I am currently uploading a file to angular directive with ...

var fd = new FormData(); fd.append("uploadedFile", scope.uploadedFile); var xhr = new XMLHttpRequest(); xhr.upload.addEventListener("progress", uploadProgress, false); xhr.addEventListenter("load", uploadComplete, false); xhr.addEventListenter("error", uploadFailed, false); xhr.addEventListenter("abort", uploadCanceled, false); xhr.open("POST", scope.postUrl); scope.uploadInProgress = true; xhr.send(fd); function uploadProgress(e){ scope.$apply(function(){ if(e.lengthComputable){ scope.progress = Math.round(e.loaded * 100 / e.total); } else { scope.progress = 'unable to compute'; } }); } ... 

Is it possible to edit this fragment using the $ http provider? I can't figure out how to keep event listeners.

+6
source share
2 answers

Short answer : you will be able soon, but not as accurately as you requested.

Several options for building functionality are discussed - displaying the base xhr object or the ability to select callbacks for methods.

See https://github.com/angular/angular.js/issues/1934 - progress events at the moment will not work.

In the meantime, I would recommend creating the object manually and using $apply update your area, just like you.

See this question for more information on how to use the service to configure, at least to start and stop events that you can catch, but no luck.

AngularJS: need to fire an event every time ajax call is fired

+3
source

Currently you can use the angular-file-upload directive, which is simple / easy and supports file overflow and upload. It uses the boot pad before angular to be able to access the private XHR object in angular and attach an event event listener to it.

 <div ng-controller="MyCtrl"> <input type="file" ng-file-select="onFileSelect($files)" multiple> </div> 

JS:

 //inject angular file upload directive. angular.module('myApp', ['angularFileUpload']); var MyCtrl = [ '$scope', '$upload', function($scope, $upload) { $scope.onFileSelect = function($files) { for (var i = 0; i < $files.length; i++) { var $file = $files[i]; $upload.upload({ url: 'my/upload/url', file: $file, progress: function(evt){ $scope.progress = parseInt(100.0 * evt.loaded / evt.total); } }).then(function(data, status, headers, config) { // file is uploaded successfully console.log(data); }); } } }]; 
+1
source

All Articles