1

I have seen a lot of solutions here in SO to upload file in Angular JS. Most of them install additional modules(like ngUpload,angular-file-upload) or creating a custom directive which is invoked as soon as the upload is done.

The custom directive way is working and i am upload to get a hook to the files uploaded. But i want the upload to start only after a button is clicked. So i tried to call the directive on click, but not able to read the file input in the directive.

Custom Directive I am using:

app.directive('fdInput', [function () {
return {
    template: '<div></div>',
    replace: true,
    link: function (scope, element, attrs) {
        element.on('change', function  (evt) {
            var files = evt.target.files;
            console.log(files[0].name);
            console.log(files[0].size);
            scope.callbackFn({file :  sfiles[0]});
        });
   }
};
}]);

Custom directive code on click:

app.directive('fdInput', [function () {
return {
    template: '<div></div>',
    replace: true,
    link: function (scope, element, attrs) {
         scope.processFile= function() {
             console.log('inside processFile method');
         };
   }
};
}]);

Is there a way that i can read the file in the second code like i did in the first one?

I want to achieve file upload on click in Angular with out including additional modules. Any help is appreciated.

1 Answer 1

1

You should be able to achieve this by accessing the controller scope in your directive.

This link here on directive scope gives some very good examples to get started.

Hope that helps!

Sign up to request clarification or add additional context in comments.

1 Comment

This concept worked for me but using this link uncorkedstudios.com/blog/… But I am now facing issue while sending the form data to the REST API. Any link as to how to send the file content?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.