[英]Define AngularJS directive using TypeScript and $inject mechanism
[英]Inject dependency to the angularjs directive using typescript
假设我有一个简单的角度指令,如下所示:
app.directive('setFocus', ['$timeout', function($timeout) {
return {
restrict: 'AC',
link: function(_scope, _element) {
$timeout(function() {
_element[0].focus();
}, 0);
}
};
}]);
如何使用Typescript编写它并在链接函数中获得$ timeout访问? 我的例子看起来像这样:
/// <reference path="../../reference.ts"/>
class SetFocus{
constructor() {
var directive: ng.IDirective = {};
directive.restrict = 'EA';
directive.scope = { };
directive.link= function ($scope, $element, $attrs) {
// How can I access $timeout here?
}
return directive;
}
}
directives.directive('setFocus', [SetFocus]);
这可能是一个愚蠢的例子,但它是我想要工作的原则,它在角度链接函数中使用注入的依赖项。
试试这种方式:
class SetFocus implements ng.IDirective {
//Directive settings
restrict :string = 'EA';
scope : any= {};
//Take timeout argument in the constructor
constructor(private $timeout: ng.ITimeoutService) {
}
link: ng.IDirectiveLinkFn = ($scope: ng.IScope, $element: ng.IAugmentedJQuery, $attrs: ng.IAttributes) => {
//refer to the timeout
this.$timeout(function() {
$element[0].focus();
}, 0);
}
//Expose a static func so that it can be used to register directive.
static factory(): ng.IDirectiveFactory {
//Create factory function which when invoked with dependencies by
//angular will return newed up instance passing the timeout argument
var directive: ng.IDirectiveFactory =
($timeout:ng.ITimeoutService) => new SetFocus($timeout);
//directive's injection list
directive.$inject = ["$timeout"];
return directive;
}
}
directives.directive('setFocus', SetFocus.factory());
这可能是你现在拥有它的方式的一个问题。 因为指令工厂没有新建,所以它的构造函数将this
作为全局对象执行。 这样你就不会有一个巨大的构造函数,并且可以用适当的类ey方式编写它。
如果您注入了许多依赖项而不是在工厂中重复参数,那么您也可以这样做:
var directive: ng.IDirectiveFactory =
(...args) => new (SetFocus.bind.apply(SetFocus, [null].concat(args)));
为了避免所有的工厂样板(以及构造函数数组),我最近编写了一个小型库(目前作为测试项目),它使指令的定义非常简单(这里省略了控制器和模板):
@Directive('userRank')
export class UserRankDirective implements ng.IDirective {
controller = UserRankDirectiveController;
restrict = 'A';
template = template;
//controllerAs: 'ctrl', set as default
replace = true;
scope = {
user: '=userRank'
}
constructor($q: ng.IQService) {
console.log('Q service in UserRankDirective:', $q);
}
}
它使用像@Directive
这样的装饰器和TypeScript编译器的自定义版本,它们在运行时使接口元数据可用(因此ng.IQService
可以转换为'$q'
并注入构造函数数组中)。 没有更多app.directive(...)
样板:一切都在装饰器中完成:)你可以在这里看一下示例应用程序代码
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.