问题描述
假设我有一个简单的 angular 指令,如下所示:
Lets say I have a simple angular directive that looks like this:
app.directive('setFocus', ['$timeout', function($timeout) {
return {
restrict: 'AC',
link: function(_scope, _element) {
$timeout(function() {
_element[0].focus();
}, 0);
}
};
}]);
如何使用 Typescript 编写此代码并在链接函数中获取 $timeout 访问权限?我的例子看起来像这样:
How can I write this using Typescript and get the $timeout accesible within the link function? My example would look something like this:
/// <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]);
这可能是一个愚蠢的例子,但这是我想要工作的原则,即在角度链接函数中使用注入的依赖项.
This might be a silly example but it is the principle I would like to get working, which is using injected dependencies in the angular link function.
推荐答案
试试这个:
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 方式编写它.
It could be a problem with the way you have it right now. Because directive factory is not newed up so its constructor will execute with this
as global object. This way you don't end up having a huge constructor as well and can write it in proper class ey manner.
如果您注入了许多依赖项而不是在工厂中重复参数,您也可以这样做:
If you have many dependencies injected instead of repeating the arguments in the factory you could as well do:
var directive: ng.IDirectiveFactory =
(...args) => new (SetFocus.bind.apply(SetFocus, [null].concat(args)));
这篇关于使用打字稿注入对 angularjs 指令的依赖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!