私はAngularJsを初めて使用しています。現在、ファイルアップロードスクリプトを作成中です。 私はウェブを検索し、いくつかのスクリプトを組み合わせて以下のコードを達成しました。クリアボタンはAngularJsのアップロードで動作しません
私の問題は、クリアボタンがクリック時にファイル名をクリアしてファイルをキューから削除する必要があることです。
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
</head>
<body ng-app = "myApp">
<div ng-controller = "myCtrl">
<input type = "file" file-model = "myFile" file-select="file"/>
<button ng-click="clear()">clear</button>
<button ng-click = "uploadFile()">upload me</button>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', ['$scope', 'fileUpload', 'fileSelect', function($scope, fileUpload, fileSelect){
$scope.uploadFile = function(){
var file = $scope.myFile;
console.log('file is ');
console.dir(file);
var uploadUrl = "/fileUpload";
fileUpload.uploadFileToUrl(file, uploadUrl);
};
$scope.clear = function() {
$scope.file = null;
};
}]);
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[0]);
});
});
}
};
}]);
app.directive('fileSelect', function() {
return function(scope, elem, attrs) {
var selector = $parse(attrs.fileSelect);
var modelSelector = elem.append(selector);
selector.bind('change', function(event) {
scope.$apply(function() {
scope[ attrs.fileSelect ] = event.originalEvent.target.files;
});
});
scope.$watch(attrs.fileSelect, function(file) {
selector.val(file);
});
};
});
app.service('fileUpload', ['$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(){
});
}
}]);
</script>
</body>
</html>
try $ scope.file = ""; –
@TirthrajBarotこれはうまくいきません、私はすでに試しました。 –
コンソールにはどのようなエラーが表示されますか? –