问题描述
最近我开始重构我正在使用 TypeScript 处理的 Angular 项目之一.由于 static $inject Array
属性,使用 TypeScript 类定义控制器非常方便,并且可以很好地处理缩小的 JavaScript 文件.并且您无需从类定义中拆分 Angular 依赖项即可获得非常干净的代码:
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 with minified JavaScript files thanks to static $inject Array<string>
property. And you get pretty clean code without splitting Angular dependencies from the class definition:
module app {
'use strict';
export class AppCtrl {
static $inject: Array < string > = ['$scope'];
constructor(private $scope) {
...
}
}
angular.module('myApp', [])
.controller('AppCtrl', AppCtrl);
}
现在我正在寻找解决方案来处理指令定义的类似情况.我发现将指令定义为函数的好习惯:
Right now I am searching for solution to handle similar case for the directive definition. I found a good practice to define the directives as function:
module directives {
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
...
}
};
}
angular.module('directives', [])
.directive('myDirective', ['toaster', myDirective]);
}
在这种情况下,我被迫在指令定义中定义 Angular 依赖项,如果定义和 TypeScript 类在不同的文件中,这很容易出错.使用 typescript 和 $inject
机制定义指令的最佳方法是什么,我正在寻找一种实现 TypeScript IDirectiveFactory
接口的好方法,但我对解决方案并不满意我找到了.
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. What is the best way to define directive with typescript and the $inject
mechanism, I was searching for a good way to implement TypeScript IDirectiveFactory
interface but I was not satisfied by the solutions I found.
推荐答案
使用类并从 ng.IDirective 继承是使用 TypeScript 的方法:
Using classes and inherit from ng.IDirective is the way to go with TypeScript:
class MyDirective implements ng.IDirective {
restrict = 'A';
require = 'ngModel';
templateUrl = 'myDirective.html';
replace = true;
constructor(private $location: ng.ILocationService, private toaster: ToasterService) {
}
link = (scope: ng.IScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes, ctrl: any) => {
console.log(this.$location);
console.log(this.toaster);
}
static factory(): ng.IDirectiveFactory {
const directive = ($location: ng.ILocationService, toaster: ToasterService) => new MyDirective($location, toaster);
directive.$inject = ['$location', 'toaster'];
return directive;
}
}
app.directive('mydirective', MyDirective.factory());
相关答案:https://stackoverflow.com/a/29223360/990356
这篇关于使用 TypeScript 和 $inject 机制定义 AngularJS 指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!