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 ng-annotate
, 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();
resource.data = data;
resource.save();
}
}
module.exports = angular.module("MyModule", [])
.factory('MyResource', MyResourceFactory)
.controller('MyController', MyController)
.config(routes);
But, on the very first line of myMethod
(var resource = new MyResource()
) execution fails:
ReferenceError: MyResource is undefined
at MyController.myMethod (myModule.module.js:214)
...
Technologies used:
How to apply ngInject to an ECMA6-class method?
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();
resource.data = data;
resource.save();
}
}