小编典典

ng-模型`(带有指令DEMO)

angularjs

我试图在类型文件的输入标签上使用ng-model:

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

但是选择文件后,在控制器中,$ scope.vm.uploadme仍未定义。

如何在控制器中获取所选文件?


阅读 280

收藏
2020-07-04

共1个答案

小编典典

我使用指令创建了一种解决方法:

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

输入标签变为:

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

或者,如果仅需要文件定义:

.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;
                });
            });
        }
    }
}]);
2020-07-04