在AngularJS中,我使用此处描述的方法来处理input type = file.
标记:
<div ng-controller="MyCtrl">
<input type="file" onchange="angular.element(this).scope().setFile(this)">
{{theFile.name}}
</div>
Run Code Online (Sandbox Code Playgroud)
控制器:
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', function($scope) {
$scope.setFile = function(element) {
$scope.$apply(function($scope) {
$scope.theFile = element.files[0];
});
};
});
Run Code Online (Sandbox Code Playgroud)
如上所述,它有点像黑客,但它主要适用于我的目的.然而,我需要的是一种在上传完成后清除文件输入的方法 - 即:来自控制器.
我可以完全破解它并使用jQuery或其他东西来找到输入元素并清除它,但希望有一些更优雅的东西.
ovi*_*diu 35
上传成功后,我从控制器中明确清除输入类型文件元素,如下所示:
angular.forEach(
angular.element("input[type='file']"),
function(inputElem) {
angular.element(inputElem).val(null);
});
Run Code Online (Sandbox Code Playgroud)
在input[type='file']选择需要的jQuery,但一切是纯角.
Tos*_*osh 11
我肯定会使用指令来完成这类任务.
app.directive('fileSelect', function() {
var template = '<input type="file" name="files"/>';
return function( scope, elem, attrs ) {
var selector = $( template );
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);
});
};
});
Run Code Online (Sandbox Code Playgroud)
注意:它使用jquery进行元素创建.
我的解决方案没有使用$ scope.
app.directive('fileChange',['UploadService',function (UploadService) {
var linker = function (element, attrs) {
element.bind('change', function (event) {
var files = event.target.files;
UploadService.upload({'name':attrs['name'],'file':files[0]});
element.val(null); // clear input
});
};
return {
restrict: 'A',
link: linker
};
}]);
Run Code Online (Sandbox Code Playgroud)
它可能会帮助你!!
HTML代码示例
<input type="file" id="fileMobile" file-model="myFile">
<button type="button" class="btn btn-danger" id="i-agree" ng-click="uploadFile()"> Upload </button>
Run Code Online (Sandbox Code Playgroud)
AngularJs代码示例
$scope.uploadFile = function () {
var file = $scope.myFile;
mobileService.uploadBulkFile(file).then(function (resp) {
if (resp !== undefined) {
$('#fileMobile').val('');
}
});
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
60146 次 |
| 最近记录: |