【发布时间】:2017-12-23 13:08:39
【问题描述】:
我有一个用 es6 编写的指令。我需要将一些服务注入到这个指令控制器中。 在 es5 中,我会这样做:
function MyDirective() {
function controller(commonService) {
commonService.doSomething(this.type);
};
return {
scope: {
type: '='
},
restrict: 'E',
controller: ['commonService', controller],
controllerAs: 'vm',
templateUrl: 'myTemplate.html',
bindToController: true
};
}
angular.module('myApp').directive('myDirective', ['commonService', MyDirective]);
这样,在 ES5 中,过去的一切都可以正常工作。 在 es6 中,我会这样做:
class MyDirective {
constructor(commonService) {
this.scope = {
type: '='
};
this.restrict = 'E';
this.controllerAs = 'vm';
this.templateUrl = 'myTemplate.html';
this.bindToController: true;
}
controller() {
commonService.doSomething(this.type);
}
}
angular.module('myApp').directive('myDirective', [('commonService') => MyDirective(commonService)]);
现在的问题是:我不能再将 commonService 注入我的控制器。 我尝试过使用
this.commonService = commonService;
在构造函数中,但不幸的是,由于某些奇怪的原因,我无法访问控制器内部的“this”。 (这不就是上课的全部意义吗?)
如何将我的 commonService 注入到控制器函数中,或者如何从控制器函数中获得对“this”的访问权?
谢谢!
【问题讨论】:
标签: javascript html angularjs angularjs-directive ecmascript-6