I have a page that has a form on it. One of the things I need to include on the page is the ability to upload a file. I am trying to do this by using another form with an in it. When the user selects the file, I want to get the file name and then perform the actual upload. From what I read, I cannot submit a form within a form, because the submit button in the inner form will also submit the outer form. I have tried looking for options and found the following page.
Can I trigger a form submit from a controller?
I thought that if I used this type of directive, then submitted it with the commit, then it should work....my problem is that for some reason when I try to access the form in my controller, it is showing as undefined. I think I need the form so that I can get the file name of the selected file...there may be a different way to achieve this than what I have tried but I haven't found it yet...
The latest controller, directive, and HTML files are below.
Controller:
$scope.uploadIt = function($form) {
console.log($form);
if ($form.$valid) {
$form.commit();
}
};
HTML:
<form editable-form name="editableForm" onaftersave="update" >
<tr>
: other fields here....
</tr>
<tr>
<td>
<form ng-form-commit name='fileForm' action="scripts/upload_file.php" method="post" enctype="multipart/form-data">
<label for="exampleInputFile">File input</label>
<input type="file" id="file" name="file">
<p class="help-block">Upload a file to link it with this project.</p>
<input type="text" name="prgGuid" id="prgGuid" value="{{programId}}" style="display:none;">
<input type="button" ng-click="uploadIt(fileForm)" name="submit" value="Upload File" class="btn btn-default">
</form>
</td>
</tr>
</form>
Directive:
app.directive("ngFormCommit", [function(){
return {
require:"form",
link: function($scope, $el, $attr, $form) {
$form.commit = function() {
$el[0].submit();
};
}
};
}]);
One more this that I will need to do....when the file is actually uploaded, I will actually be changing the file name so it is unique. Once the file is uploaded, I will need to pass back the new file name to my controller so I can store/display it. So I will need the original name the user selected and the new name...my php file will pass it back. I was thinking at first that maybe I could use a $http.post to submit the form and get the information back, but I couldn't get the file name the user selected. I was thinking if I could use the http.post to process the php file, then I wouldn't run into the form inside form, submit issue.
Please can someone tell me the easiest way to accomplish uploading a file with the form inside form constraints I have? I have been trying various things from posts I have seen but on here but I haven't found anything similar....please help. Thanks.