Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create two-way directive for AngularJS?

First week with AngularJS, I used the code for file uploading directive from https://uncorkedstudios.com/blog/multipartformdata-file-upload-with-angularjs

app.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]);
                });
            });
        }
    };
}]);

It works great when reading the content -- user selects the file, I read it in JS, and then after sending it to server I would like to clear it (by setting null). And here is the problem -- it does not work, the file name in <input> is not changed.

How should I modify it get two-way directive?

like image 592
greenoldman Avatar asked Dec 09 '25 05:12

greenoldman


1 Answers

Angularjs doesn't seem to have support for two-way binding for an input element with type 'file'. Refer issue.

A simple way to achieve what you are looking for could be through resetting the input value after the file upload is done. Set an id, say 'fileInput' for the input field, and then use:

document.getElementById("fileInput").value = "";

to reset the input value to blank.

Here's the Js fiddle for the same.

like image 200
Aditi Avatar answered Dec 10 '25 21:12

Aditi