0

I am trying to upload a file to a cloud using the ng-file-select directive of Angular. The function called for uploading the image should be called only when the form containing the upload field is submitted. The code is given below:

<form class="form-horizontal" name="reviewEntry" role="form" ng-controller="reviewController" ng-submit="submitFeedback(reviewer.image)" novalidate>   
    ...
    <input type="file" id="image" name="image" ng-file-select="onFileSelect($files)" accept="image/*" ngf-max-size="5MB" ngf-model-invalid="errorFiles">
    ...       
</form>

My controller code:

$scope.submitFeedback = function(file) {

    $scope.showSuccess = false;
    $scope.message = "Loading ...";

    var review = {
        name: $scope.reviewer.name,
        model: $scope.reviewer.model,
        image: $scope.reviewer.image,
        review: $scope.reviewer.review
    };

    $scope.onFileSelect = function(files) {

    if (files && files.length) {
        $scope.file = files[0];
    }
    alert("ON FILE SELECT");

    Upload.upload({

        url: '/images/upload',
        method: 'POST',
        file: $scope.file

    }).success(function(data) {
        console.log("SUCCESS: " + data);
    }).error(function(err) {
        console.log("ERROR: " + err.message);
    });

    ...
};

However, onFileSelect inside submitFeedback is never called (no alert box) - the upload should happen only after the submit button is pressed. I am relatively new to Angular - can anyone help me fix this?

1 Answer 1

1

Edit: onFileSelect is called on file select event. You should not define that function inside the submitFeedback function. So move $scope.onFileSelect outside of the $scope.submitFeedback.

Also when you move it, you need to change it and let the $scope.submitFeedback have the logic for uploading, not the $scope.onFileSelect function.

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

2 Comments

But if I move the uploading logic to $scope.submitFeedback, it makes no sense to have the $scope.onFileSelect function at all. Also, I want the uploading to be done only when the submit button has been pressed.
OK, I got it to work the way you said. I set a $scope.file variable in the $scope.onFileSelect function, and used it in the submit function. Thank you!

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.