Define AngularJS directive using TypeScript and $inject mechanism

后端 未结 9 1702
死守一世寂寞
死守一世寂寞 2020-12-12 15:04

Recently I started refactoring one of the Angular projects I am working on with TypeScript. Using TypeScript classes to define controllers is very convenient and works well

9条回答
  •  南方客
    南方客 (楼主)
    2020-12-12 15:33

    In this case I am forced to define angular dependencies in the directive definition, which can be very error-prone if the definition and typescript class are in different files

    Solution:

     export function myDirective(toaster): ng.IDirective {
        return {
          restrict: 'A',
          require: ['ngModel'],
          templateUrl: 'myDirective.html',
          replace: true,
          link: (scope: ng.IScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes, ctrls) => 
            //use of $location service
            ...
          }
        };
      }
      myDirective.$inject = ['toaster']; // THIS LINE
    

提交回复
热议问题