我正在开发一个旧项目,它是用AngularJS 1.5.7开发的。我想把TypeScript用于新开发的东西。因此,只有新添加的东西应该在TypeScript中--目前还没有完全迁移。
我找到了如何用TypeScript在AngularJS上编写指令。
import * as angular from 'angular';
angular
.module('starter.directives')
.directive('lateralScrollbar', ['$timeout', ($timeout) =>
new (class {
restrict = 'A';
constructor(
private $timeout
) { }
link(scope: ng.IScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes) {
let directive = this;
new (class {
constructor(
scope: ng.IScope,
element: ng.IAugmentedJQuery,
attrs: ng.IAttributes
) {
scope.something = 'Loading';
/** 1. How to optimize hat "directive" is not needed here? Maybe that I can use "this" instead or "parent" */
directive.$timeout(() => scope.something = 'OK', 1000);
}
})(scope, element, attrs);
}
/** 2. How to optimize that I can pass the arguments with that the function was called. For example fn.apply(); and ...args? */
})($timeout)
]);您可以看到有两个评论。
所以第一个很有趣。我认为。目前,我尽可能使用依赖项数组和末尾的函数调用该指令。但是,它的复杂性是不必要的:-(这个函数在其中创建了类的一个对象。然后这个类有一个链接函数,它将directive定义为this,这样我就可以在其中使用传递的参数。(即$timeout)。
第二件事是,我现在定义$timeout变量四次。1 x关于角指令的依赖关系。1x类的构造函数。用于一级初始化的1x参数。函数的1x,它是第一类的包装器。
所以这是我的一次尝试,但是失败了,因为它不能处理这个...args事件。不知道如何优化。
import * as angular from 'angular';
angular
.module('starter.directives')
.directive('lateralScrollbar', ['$timeout', (...args) =>
new (class {
restrict = 'A';
constructor(
private $timeout
) { }
link(scope: ng.IScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes) {
let directive = this;
new (class {
constructor(
scope: ng.IScope,
element: ng.IAugmentedJQuery,
attrs: ng.IAttributes
) {
scope.something = 'Loading';
/** 1. How to optimize hat "directive" is not needed here? Maybe that I can use "this" instead or "parent" */
directive.$timeout(() => scope.something = 'OK', 1000);
}
})(scope, element, attrs);
}
/** 2. How to optimize that I can pass the arguments with that the function was called. For example fn.apply(); and ...args? */
})(args)
]);错误: TS2554:预期有1个参数,但得到0.
也许有人能帮我:-)谢谢提前了!
发布于 2017-11-06 22:32:27
https://stackoverflow.com/questions/46692046
复制相似问题