In AngularJS, I'm using the approach described here to handle input type=file.
Markup:
<div ng-controller="MyCtrl"> <input type="file" onchange="angular.element(this).scope().setFile(this)"> {{theFile.name}} </div>
Controller:
var myApp = angular.module('myApp', []); myApp.controller('MyCtrl', function($scope) { $scope.setFile = function(element) { $scope.$apply(function($scope) { $scope.theFile = element.files[0]; }); }; });
As mentioned it's a bit of a hack, but it mostly works for my purposes. What I need however is a way to clear the file input after the upload has finished - ie: from the controller.
I could completely hack it and use jQuery or something to find the input element and clear it, but was hoping for something a little more elegant.
import { ViewChild } from '@angular/core'; ViewChild allows you to set a reference variable to your input, using that you can clear the value of input. After clearing the value of input using the reference variable, the selected file will be reset.
bind('focus', function() { // Clear any files currently selected in #upload-file $('#upload-file'). val(''); }) ; // Choose uploading new one - this works ok $('#upload-file'). bind('focus', function() { // Clear any files currently selected in #select-file $('#select-file').
Upon a successful upload, I clear up the input type file elements explicitly from my controller, like so:
angular.forEach( angular.element("input[type='file']"), function(inputElem) { angular.element(inputElem).val(null); });
The input[type='file']
selector requires jQuery, but everything else is plain Angular.
I would definitely use directive for this kind of task.
http://plnkr.co/edit/xLM9VX
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); }); }; });
note: it is using jquery for element creation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With