Angularjs+Typescsript: Best approach to upload file (using controlleras syntax)

2.5k Views Asked by At

I have a working example below, but I think it's not the right approach!

My requirments are:

  • I don't want to use external plugins!
  • Use controlleras syntax
  • Use Typescript

Html:

<input type="file" name="file" onchange="angular.element(this).scope().uploadFile(this.files)" />

Controller:

module Test {
    export class TestController {
        MessageUpload: string;
        vm: any;

        static $inject = [ 'Factory','$state', '$scope'];

        constructor(private Factory:IFactory, private $state: ng.ui.IStateService, private $scope: any) {
            $scope.vm = this;
            $scope.uploadFile = this.uploadFile;
            this.vm = this;
        }

        /* ... */
        /* ... */
        /* ... */

        get(){/* .... */}

        uploadFile(files) {
            this.vm.MessageUpload = 'Uploading file. Please wait...';
            var fd = new FormData();
            fd.append('file', files[0]);

            this.vm.Factory.upload(fd).then((r) => {
                this.vm.MessageUpload = 'Completed ...';
                this.vm.get();
            });
        }
    }
}

Last note:

  • in uploadFile(): this is referred to $scope so I have to pass controller instance somehow to be able to access MessageUpload and get(). Even in get() function this is referred to $scope.

Does anyone know how to refactor this to be able to achieve uploading and using this as reference to the controller.

2

There are 2 best solutions below

1
On

onchange

There is angular world ($digest) and there is the outside world (in v1 atleast). So you can't just use a standard event handler to do stuff.

I don't want to use external plugins!

Sure. Then copy the code from any number of already written plugins.

0
On

Replace the line: $scope.uploadfile = this.uploadFile;

With: $scope.uploadFile = (file):void => this.uploadFile(file);

* this is how to assign the function to the scope *

Remove the line: this.vm = this;