Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clear a file input from Angular JS

Tags:

angularjs

In AngularJS, I'm using the approach described here to handle input type=file.

  • https://groups.google.com/forum/?fromgroups=#!topic/angular/-OpgmLjFR_U
  • http://jsfiddle.net/marcenuc/ADukg/89/

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.

like image 539
Brad Robinson Avatar asked Feb 26 '13 01:02

Brad Robinson


People also ask

How do you reset the selected file with an input tag type in angular 9?

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.

How do you delete selected files on file upload control after a successful upload?

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').


2 Answers

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.

like image 51
ovidiu Avatar answered Sep 22 '22 11:09

ovidiu


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.

like image 30
Tosh Avatar answered Sep 21 '22 11:09

Tosh