本文介绍了用于<< input type =" file"/>`的ng-model(带有指令DEMO)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试在类型为file的输入标签上使用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" />
或者仅需要文件定义:
.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)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!