Dismiss
Announcing Stack Overflow Documentation

We started with Q&A. Technical documentation is next, and we need your help.

Whether you're a beginner or an experienced developer, you can contribute.

Sign up and start helping → Learn more about Documentation →

I need to define an angular directive with a link function. (1) The following code works just as expected - but the part about dependency seems to be unnecessarily complicated. Can this be done any cleaner?

(2) Can I use the this syntax in a link function instead of scope.any or write the link function as ts-class?

import {myApp} from '../../../angular-modules';

interface MyDirectiveScope extends ng.IScope {
  requiredController:any;
}


function MyDirectiveLink(scope: MyDirectiveScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes, controllers: any) {const vm = scope;
  scope.requiredController = controllers[0];
}


export class MyDirective implements ng.IDirective {

  constructor(private myService) {
  }

  public restrict = 'E';
  public require = ['^requiredDirective'];
  public templateUrl: '/components/myDirective/myDirective.template.html';
  public replace = true;

  public link = MyDirectiveLink;

  static factory(): ng.IDirectiveFactory {
    const directive = (myService) => new MyDirective(myService);
    directive.$inject = ['myService'];
    return directive;
  }
}


myApp.directive('myDirective', MyDirective.factory());
share|improve this question

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.