How to clear a file input from Angular JS

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.

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.

my solution without using $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
    };
}]);

It might help you!!

HTML code sample

 <input type="file" id="fileMobile" file-model="myFile">
 <button type="button" class="btn btn-danger" id="i-agree" ng-click="uploadFile()"> Upload </button>

AngularJs code sample

$scope.uploadFile = function () {
    var file = $scope.myFile;
    mobileService.uploadBulkFile(file).then(function (resp) {
        if (resp !== undefined) {
            $('#fileMobile').val('');
        }
    });
};