//inject angular file upload directives and services.
var app = angular.module('fileUpload', ['angularFileUpload']);

app.controller('MyCtrl', ['$scope', '$upload', '$rootScope', function ($scope, $upload, $rootScope)
    {
    var fileupload = this;
    fileupload.$rootScope = $rootScope;

    $scope.$watch('files', function ()
        {
        $scope.upload($scope.files);
        });

    $scope.upload = function (files)
        {
        if (files && files.length)
            {
            for (var i = 0; i < files.length; i++)
                {
                var file = files[i];
                $upload.upload(
                    {
                    url: '/controller/repository?' + file,
                    fields: {'username': $scope.username},
                    file: file
                    }).progress(function (evt)
                        {
                        var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
                        console.log('progress: ' + progressPercentage + '% ' + evt.config.file.name);
                        }).success(function (data, status, headers, config)
                            {
                            fileupload.$rootScope.$broadcast('repositoryUploaded');
                            console.log('file ' + config.file.name + 'uploaded. Response: ' + data);
                            });
                }
            }
        };
    }]);