ng-file-upload: Don't call ngf-change with an empty files parameter

@danialfarid What I’m seeing is that ngf-change is being called TWICE. Once when you click the button and the file chooser dialog opens and once when the dialog closes after selecting a file.

I added this to your fiddle…

    $scope.upload = function (files) {
        alert('called from upload. files is: ' + files);

Whatever is calling it shouldn’t call it the first time. There is no reason to call $scope.upload if files is null. This would allow me to remove the null check and simplify things greatly.

About this issue

  • Original URL
  • State: closed
  • Created 9 years ago
  • Comments: 20 (17 by maintainers)

Commits related to this issue

Most upvoted comments

2017 update:

I have a form that is set up to validate on whether or not a file was uploaded. When a user would cancel out of the dialog box, the upload field would be invalid because the ng-model had changed to null.

Since the API has since changed from the suggestions in this issue but this page is still the top result when searching “ng-file-upload change empty,” I figured I’d note my solution:

I simply hooked into the ngf-before-model-change function, set a temporary controller variable, and reset my “real” value when ngf-change was called. It looks a little like this:

form.html

<a id="fileUpload"
     href=""
     name="fileUpload"
     class="fa fa-2x fa-upload"
     ng-model="ctrl.file"
     ngf-select
     ngf-min-size="1"
     ngf-change="ctrl.uploadFile($file)"
     ngf-before-model-change="ctrl.setTmpFile($file)"
     required>
</a>

controller.js

setTmpFile (newFile) {
    // If new file exists, set the temporary variable
    // newFile will be null if the user cancels out of the dialog box
    if(newFile){
        this.tmpFile = newFile;
    };
};

uploadFile (newFile, index) {
    // Set the "real" model to the temporary file
    this.file = this.tmpFile;

    ...
    Do other stuff
};

Now, the ng-model variable ctrl.file is either a real file (the user selected one in the dialog) or the file it was previously (the user cancels out of the box).