我试图在类型文件的输入标签上使用ng-model:
<input type="file" ng-model="vm.uploadme" />
但是选择文件后,在控制器中,$ scope.vm.uploadme仍未定义。
如何在控制器中获取所选文件?
我使用指令创建了一种解决方法:
.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; }); }); } } }]);