以下是我的HTML表单:
<form name="myForm" ng-submit="">
<input ng-model='file' type="file"/>
<input type="submit" value='Submit'/>
</form>我想从本地机器上传一个图像,并希望读取上传文件的内容。所有这些我都想用AngularJS来做。
当我试图打印$scope.file的值时,它是未定义的。
发布于 2015-02-03 10:21:17
使用指令很容易
Html:
<input type="file" file-upload multiple/>联署材料:
app.directive('fileUpload', function () {
return {
scope: true, //create a new scope
link: function (scope, el, attrs) {
el.bind('change', function (event) {
var files = event.target.files;
//iterate files since 'multiple' may be specified on the element
for (var i = 0;i<files.length;i++) {
//emit event upward
scope.$emit("fileSelected", { file: files[i] });
}
});
}
};在该指令中,我们确保创建了一个新的作用域,然后侦听对文件输入元素所做的更改。当检测到更改时,将事件发送到以文件对象为参数的所有祖先作用域(向上)。
在您的控制器中:
$scope.files = [];
//listen for the file selected event
$scope.$on("fileSelected", function (event, args) {
$scope.$apply(function () {
//add the file object to the scope's files collection
$scope.files.push(args.file);
});
});然后在ajax调用中:
data: { model: $scope.model, files: $scope.files }http://shazwazza.com/post/uploading-files-and-json-data-in-the-same-request-with-angular-js/
https://stackoverflow.com/questions/18571001
复制相似问题