本文介绍了`<input type="file"/>` 的 ng-model(带有指令 DEMO)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试在带有类型文件的输入标签上使用 ng-model:
I tried to use ng-model on input tag with type file:
<input type="file" ng-model="vm.uploadme" />
但是选择文件后,在控制器中,$scope.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?
推荐答案
我用指令创建了一个解决方法:
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]);
});
}
}
}]);
输入标签变成:
<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;
});
});
}
}
}]);
这篇关于`<input type="file"/>` 的 ng-model(带有指令 DEMO)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!