Vish
Vish

Reputation: 280

Same file can not be uploaded twice in angularjs using fileModel

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?

Upvotes: 1

Views: 2498

Answers (2)

You don't have to alter your HTML or controller. As your directive is restrict to attribute. Its better use element.on('click',fn) for this scenario.

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.on('click', function(){
                angular.element("input[type='file']").val(null);
            });*
            element.bind('change', function(){
                scope.$apply(function(){
                    modelSetter(scope, element[0].files[0]);
                });
            });
        }
    };
}]);

Upvotes: 0

Vish
Vish

Reputation: 280

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..!!

Upvotes: 6

Related Questions