Same file can not be uploaded twice in angularjs using fileModel

Issue

I am using angular js fileModel directive to upload file, which is as below

angular.module('MyProject').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]);
                });
            });
        }
    };
}]);

And I am using the same in html as below,

 <input type='file' class="imgInp" file-model="tenantLogoFile"/>

If I select one file then Its fine for me to capture the file chosen by user by using $watch on “tenantLogoFile”. But if I am supposed to upload same file (Without refreshing page) immediately again, $watch does not get fired and ultimately I am unable upload the file.

I tried setting $scope.tenantLogoFile = null after first time successful upload, but no use, Can anyone help me please?

Solution

Anyways guys I found a workaround as below,

<input type='file' file-model="myFile" ng-click="clearFileSelection();"/>

I wrote a function named “clearFileSelection” in controller and called it on every subsequent click on the file chooser button, so that the previous file contents got cleared, function code is as below.

$scope.clearFileSelection = function(){
        angular.element("input[type='file']").val(null);
    }

I hope this will definitely help some other strugglers like me.. Happyyy Coding..!!

Answered By – Vish

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published