11

Using Angular 1.4 with ES6/7 and Babel, I can successfully inject parameters into a class named Controller with this code after the class block:

class Controller {
    constructor($scope, $state, $window) {...}
    ...
}
Controller.$inject = ["$scope", "$state", "$window"]

However, it would be cleaner to see the inject parameters right above the constructor. I've seen other people use static $inject, but I get an error. Here's what I'm attempting:

class Controller {
    static $inject = ["$scope", "$state", "$window"]
    constructor($scope, $state, $window) {...}
    ...
}

Why does that cause this error? It seems to work for other people.

Unexpected token (2:11)
  1 | class Controller {
  2 |     static $inject = ["$scope", "$state", "$window"]
    |  
              ^
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
Kip
  • 560
  • 7
  • 16

2 Answers2

15

That is an experimental proposed syntax. In Babel, you'd have to enable es7.classProperties. Pass

optional: ['es7.classProperties']

to babel. The exact method depends on how you are transpiling.

If you wanted to do standard ES6, you could also do

static get $inject(){ return ["$scope", "$state", "$window"]; }
loganfsmyth
  • 156,129
  • 30
  • 331
  • 251
  • Thank you. This is what I was missing. I added the following to gulp and now it works. `.transform(babelify.configure({ optional: ["es7.classProperties"] }))` – Kip Jul 25 '15 at 19:00
1

Another approach would be use $injector.annotate(fn), which Angular uses for dependency injection, and which allows you to get arguments of the function you pass to it. You could utilize it to get the names of all constructor() parameters, and retrieve them using $injector.get().

Here's a link to answer in another thread, and a direct link to a fiddle with a demo.

Community
  • 1
  • 1
Maciej Gurban
  • 5,615
  • 4
  • 40
  • 55