我有一个用 es6 编写的指令。我需要将一些服务注入(inject)到这个指令 Controller 中。 在 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 注入(inject)到我的 Controller 中。 我试过用
this.commonService = commonService;
在构造函数中,但不幸的是,出于某种奇怪的原因,我无法访问 Controller 内部的“this”。 (这不是一开始类的全部意义吗?)
如何将我的 commonService 注入(inject)到 Controller 函数中,或者如何从 Controller 函数中获取对“this”的访问权限?
谢谢!
最佳答案
一种选择是将 Controller 定义为一个类。
The DEMO
class MyDirective {
constructor() {
this.scope = {
type: '@'
};
this.restrict = 'E';
this.controller = 'myDirectiveCtrl',
this.controllerAs = 'vm';
this.template = `
<fieldset>
myDir type={{vm.type}}
<br> Service {{vm.serviceType}}
</fieldset>`;
this.bindToController = true;
}
}
class MyDirectiveCtrl {
constructor(commonService) {
this.commonService = commonService;
}
$onInit() {
this.serviceType = this.commonService.doSomething(this.type);
}
}
MyDirectiveCtrl.$inject = ['commonService'];
angular.module('myApp',[])
.directive('myDirective', MyDirective)
.controller("myDirectiveCtrl", MyDirectiveCtrl)
.value("commonService", {
doSomething: (type) => ("--"+type+"--")
})
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="myApp">
<h1>ES6 Directive Demo</h1>
<my-directive type="IDK"></my-directive>
</body>
关于javascript - 如何在 ES6 中注入(inject)指令 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45170610/