2

I have the following code:

<input onchange="angular.element(this).scope().filesChanged(this)" fileInput="controlFormCtrl.formData.episodeFile">

The file selected, will be passed to the scope, and will be accessible inside my controller in this way:

  var thisScope = this;
  var rootScope = $root;
  var ctrlScope = $scope;
  ctrlScope.filesChanged = function(elm) {
    thisScope.file = elm.files[0];
  }

elm.files has the following data:

lastModified: 1485109128000
lastModifiedDate: Sun Jan 22 2017 19:18:48 GMT+0100 (CET)
name:"border-image.png"
size:1353
type:"image/png"
webkitRelativePath:""
__proto__: File

However the thisScope.file is not being set.

What can I do to fix the issue?

5
  • ctrlScope.file instead of thisScope.file would work, however I am using controllerAs as i have multiple controllers nested under eachother. Commented Jan 22, 2017 at 19:50
  • 2
    My guess would be that you need to run ctrlScope.$apply(); to let angular know that thisScope has changed. Commented Jan 22, 2017 at 20:00
  • @RaphaelRafatpanah Good shout, since having to use onchange instead of ng-change (which isn't supported for this type of input), Angular won't have ran a $digest cycle. Commented Jan 22, 2017 at 20:09
  • @RaphaelRafatpanah it halfly worked, the variable is still empty or at list it looks like, the problem is that the datatype of elm.files is FileList which is not a simple array. Commented Jan 22, 2017 at 20:16
  • Maybe that is because you need to $apply() after the file is loaded since it is an async event. Commented Jan 22, 2017 at 20:26

1 Answer 1

1

You need to run ctrlScope.$apply(); to let angular know that thisScope has changed, however, this should only been run after the FileReader has loaded the file.

I recommend using the ngf-select directive to handle file uploads.

https://github.com/danialfarid/ng-file-upload

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

Comments

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.