0

I have an input file upload in a modal and I'm trying to handle its onChange event. I created a directive for the custom onChange handler for input file upload by following this solution: https://stackoverflow.com/a/19647381/769326

This is my code in ES6:

class FileUploadOnChange {
  constructor() {
    this.restrict = 'A';
  }

  link(scope, element, attrs) {
    const onChangeHandler = scope.$eval(attrs.fileUploadOnChange);
    element.bind('change', onChangeHandler);
  }

  static directiveFactory() {
    FileUploadOnChange.instance = new FileUploadOnChange();
    return FileUploadOnChange.instance;
  }
}

class MyController {
  constructor() {
    this.test = 'Hello, World';
  }

  doSomething(e) {
    console.log(this);
  }
}

angular.module('MyApp', [])
  .directive('fileUploadOnChange', FileUploadOnChange.directiveFactory)
  .component('myFileUpload', {
    template: '<input type="file" file-upload-on-change="$ctrl.doSomething">',
    controller: MyController
  });

However, when I select a file, the value of this when I log it in doSomething is the input element and not the controller. How do I pass the controller context to the changeHandler? Thank you.

Also, here's a fiddle.

Community
  • 1
  • 1
dork
  • 4,396
  • 2
  • 28
  • 56

1 Answers1

0

Okay, so I basically did what was in the SO link in my question but added a getScope function to, well, get the scope you're looking for. It's a simple recursive function to return the scope with your controller alias:

function getScope(scope, controllerAlias) {
  if (controllerAlias in scope) {
    return scope[controllerAlias];
  } else {
    getScope(scope.$parent, controllerAlias);
  }
}

So in the fiddle, you just have to call getScope and pass this and your controller alias, which by default is $ctrl.

const scope = getScope(this, '$ctrl');
dork
  • 4,396
  • 2
  • 28
  • 56