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

后端 未结 12 2260
北恋
北恋 2020-11-21 06:40

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


But after selecting a file, in

12条回答
  •  囚心锁ツ
    2020-11-21 06:55

    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:

    
    

    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;
                    });
                });
            }
        }
    }]);
    

提交回复
热议问题