AngularJS Dependency Injection with ES6

ES6 might be confusing at first – especially when using angular 1.X, which is still ES5.

One obstacle is injecting services into directives.  It doesn’t work as one might think.  The way to do it is, to inject the service into the directive’s controller, and then use it in the controller’s context (this) which is injected into the directive.

Confusing? Look at the code:

class CesiumDirective {
constructor () {
‘ngInject’;

let directive = {
restrict: ‘E’,
controller: CesiumController,
templateUrl: ‘app/components/cesiumModule/cesium.html’,
link: function(scope, element, attrs, ctrl){
ctrl.cesiumService.viewer = (new Cesium.Viewer(element[0]));
angular.element(ctrl.cesiumService.viewer.canvas).height(element.height());
}
};

return directive;
}
}

class CesiumController {
constructor (cesiumService) {
‘ngInject’;

// “this.creation” is avaible by directive option “bindToController: true”
this.cesiumService = cesiumService;
}
}

export default CesiumDirective;

Leave a Reply