// Module
// ------
var upload = angular.module('upload', []);
// Directive
// ---------
upload.directive('fileChange', function () {
var linker = function ($scope, element, attributes) {
// onChange, push the files to $scope.files.
element.bind('change', function (event) {
var files = event.target.files;
$scope.$apply(function () {
for (var i = 0, length = files.length; i < length; i++) {
$scope.files.push(files[i]);
}
});
});
};
return {
restrict: 'A',
link: linker
};
});
// Factory
// -------
upload.factory('uploadService', ['$rootScope', function ($rootScope) {
return {
send: function (file) {
var data = new FormData(),
xhr = new XMLHttpRequest();
// When the request starts.
xhr.onloadstart = function () {
console.log('Factory: upload started: ', file.name);
$rootScope.$emit('upload:loadstart', xhr);
};
// When the request has failed.
xhr.onerror = function (e) {
$rootScope.$emit('upload:error', e);
};
// Send to server, where we can then access it with $_FILES['file].
data.append('file', file, file.name);
xhr.open('POST', '/echo/json');
xhr.send(data);
}
};
}]);
// Controller
// ----------
upload.controller('UploadCtrl', ['$scope', '$rootScope', 'uploadService', function ($scope, $rootScope, uploadService) {
// 'files' is an array of JavaScript 'File' objects.
$scope.files = [];
$scope.$watch('files', function (newValue, oldValue) {
// Only act when our property has changed.
if (newValue != oldValue) {
console.log('Controller: $scope.files changed. Start upload.');
for (var i = 0, length = $scope.files.length; i < length; i++) {
...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.