javascript - 如何在 ES6 中注入(inject)指令 Controller

标签 javascript html angularjs angularjs-directive ecmascript-6

我有一个用 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/

相关文章:

javascript - 英特尔 xdk 数据库

javascript - 在 firefoxaddonsdk 中使用第三方 api

javascript - 在javascript中获取按钮的值

ajax - 一个站点有多个 AngularJS 应用程序?

java - 通过javascript将自动生成的数字插入数据库表

html - Bottle 路线添加CSS文件

html - Chrome 认为有滚动条并忽略 100% 宽度

javascript - 如何删除 Angular js中的表格行?

angularjs - 使用angularjs禁用数字输入的箭头键

javascript - 尝试在 WordPress 中使用 Ajax 时收到 400 错误请求