タイプファイルの入力タグで ng-model を使用しようとしました:
<input type="file" ng-model="vm.uploadme" />
しかし、ファイルを選択した後、コントローラーでは、$scope.vm.uploadme はまだ未定義です。
コントローラーで選択したファイルを取得するにはどうすればよいですか?
ベストアンサー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;
});
});
}
}
}]);