NG-模型&LT;输入类型=&QUOT;文件&QUOT; /&GT; [英] ng-model for <input type="file"/>
本文介绍了NG-模型&LT;输入类型=&QUOT;文件&QUOT; /&GT;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试着输入标签使用NG-模型类型的文件:
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标签就变成了:
And the input tag becomes:
<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;
});
});
}
}
}]);
这篇关于NG-模型&LT;输入类型=&QUOT;文件&QUOT; /&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文