我在使用AngularJS + Material和上传对话框时遇到了一些问题。我认为原因与范围有关,因为当我选择要上传的文件并单击 md-button 时,console.log命令(在控制器块中)显示我" 文件未定义 "并且后端没有到达数据。
这是我的代码。
模板
<md-dialog aria-label="Carica foto">
<form ng-cloak>
<md-toolbar>
<div class="md-toolbar-tools">
<h2>Upload photo</h2>
<span flex></span>
<md-button class="md-icon-button" ng-click="cancel()">
<md-icon md-svg-src="img/icons/ic_close_24px.svg" aria-label="Close dialog"></md-icon>
</md-button>
</div>
</md-toolbar>
<md-dialog-content>
<div class="md-dialog-content">
<p>Choose photo</p>
<br/><br/>
<input type = "file" file-model="fotoBadge"/>
</div>
</md-dialog-content>
<md-dialog-actions layout="row">
<span flex></span>
<md-button ng-click="uploadFile()">Upload</md-button>
</md-dialog-actions>
</form>
</md-dialog>
指令
app.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function(){
scope.$apply(function(){
modelSetter(scope, element[0].files);
});
});
}
};
}]);
服务
app.service('fileUploadSrv', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl){
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined} })
.success(function(){
})
.error(function(){
}); }
}]);
控制器
function DialogController($scope, $mdDialog) {
$scope.hide = function() {
$mdDialog.hide();
};
$scope.cancel = function() {
$mdDialog.cancel();
};
$scope.uploadFile = function(answer) {
var file = $scope.fotoBadge;
console.log('file is ' + file);
var uploadUrl = "/be/fileUpload";
fileUploadSrv.uploadFileToUrl(file, uploadUrl);
$mdDialog.hide(answer);
};
}
提前致谢。
的Davide