Bob Bob - 2 years ago 160
AngularJS Question

ECMA6 class-based controller with babel and ng-annotate/ngInject results in ReferenceError

I've an Angular 1.4 controller with a method that depends on a resource service. I've annotated the constructor of that class with

, but still, Angular curses that service can't be found in the method:

var MyResourceFactory = require("myResource.service");

class MyController {
// @ngInject
constructor($location, $stateParams, $state, MyResource) {
... // some initialization code

myMethod(data) {
var resource = new MyResource(); = data;;

module.exports = angular.module("MyModule", [])
.factory('MyResource', MyResourceFactory)
.controller('MyController', MyController)

But, on the very first line of
var resource = new MyResource()
) execution fails:

ReferenceError: MyResource is undefined
at MyController.myMethod (myModule.module.js:214)

Technologies used:

  • Angular 1.4

  • Webpack

  • Babel

  • ng-annotate

How to apply ngInject to an ECMA6-class method?

Answer Source

MyResource is a variable local to constructor method and it's not available outside. Usual approach in such cases, is to make it public property:

class MyController {
    // @ngInject
    constructor($location, $stateParams, $state, MyResource) {
        this.MyResource = MyResource;
        // ... some initialization code

    myMethod(data) {
        var resource = new this.MyResource(); = data;;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download