Search code examples
angularjsangularjs-ng-modelangularjs-fileupload

ng-model for `<input type="file"/>` (with directive DEMO)


I tried to use ng-model on input tag with type file:

<input type="file" ng-model="vm.uploadme" />

But after selecting a file, in controller, $scope.vm.uploadme is still undefined.

How do I get the selected file in my controller?


Solution

  • I created a workaround with directive:

    .directive("fileread", [function () {
        return {
            scope: {
                fileread: "="
            },
            link: function (scope, element, attributes) {
                element.bind("change", function (changeEvent) {
                    var reader = new FileReader();
                    reader.onload = function (loadEvent) {
                        scope.$apply(function () {
                            scope.fileread = loadEvent.target.result;
                        });
                    }
                    reader.readAsDataURL(changeEvent.target.files[0]);
                });
            }
        }
    }]);
    

    And the input tag becomes:

    <input type="file" fileread="vm.uploadme" />
    

    Or if just the file definition is needed:

    .directive("fileread", [function () {
        return {
            scope: {
                fileread: "="
            },
            link: function (scope, element, attributes) {
                element.bind("change", function (changeEvent) {
                    scope.$apply(function () {
                        scope.fileread = changeEvent.target.files[0];
                        // or all selected files:
                        // scope.fileread = changeEvent.target.files;
                    });
                });
            }
        }
    }]);