schmod / babel-plugin-angularjs-annotate

Add Angular 1.x dependency injection annotations to ES6 code
http://schmod.github.io/babel-plugin-angularjs-annotate
MIT License
241 stars 27 forks source link

Smart assign to `this` in constructors #27

Open ianldgs opened 6 years ago

ianldgs commented 6 years ago
angular.module('app').controller('Ctrl', class Ctrl {
  /* @ngInject */
  constructor($scope) {
    //some code
  }
});

could become:

angular.module('app').controller('Ctrl', class Ctrl {
  static $inject = ['$scope']
  constructor() {
    [this.$scope] = arguments;
    //some code
  }
});
schmod commented 6 years ago

TypeScript-style automatic property assignment is probably going to remain outside of the scope of this package. It would create unexpected behaviors for a lot of users, and there are many edge-cases that would be difficult to implement.

However, you raise a good point that your first example does not work unless ES5 transformations are enabled, or Ctrl is declared outside of angular.module().

angular.module('app').controller('Ctrl', class Ctrl {
  /* @ngInject */
  constructor($scope) {
    //some code
  }
});

However, this does (currently) work:

class Ctrl {
  constructor($scope) {
    this.$scope = $scope;
  }

  dostuff() { this.foo='baz'; }
};

angular.module('app').controller('Ctrl', Ctrl);

I'll keep this open as a bug until that's fixed.

ianldgs commented 6 years ago

That is unfortunate. How about adding options to ngInject?

Something like: /* @ngInject({autoAsign: true}) */

This is how annotations works in other languages.

About the issue of ngInject inside angular.module(), I didn't notice, as I use ES7 transformers, but I used it alot.-

schmod commented 6 years ago

babel-plugin-auto-assign might do the thing that you're looking for.

It's not necessarily an Angular 1.x-specific feature.

georgecrawford commented 5 years ago

Hi @schmod. The issue you describe in the second part of https://github.com/schmod/babel-plugin-angularjs-annotate/issues/27#issuecomment-318678752 is exactly my problem. I was expecting this plugin to detect and convert a controller class defined inside angular.module(), but as you point out it does not.

Can you explain whether a fix is planned for this, and if not, what options I have as a workaround? What do you mean by unless ES5 transformations are enabled, for example?