【发布时间】:2016-07-12 16:30:08
【问题描述】:
堆栈: 打字稿 1.7 + Angular 1.49
总结:
我有一个指令。我想$inject angular 的$timeout 服务。它在指令的控制器函数中运行良好,但在链接函数中运行良好。我错过了什么?
问题:
- 我做错了什么?
- 有没有更好的方法来
$inject$timeout依赖? - 为什么
$timeout服务可以在指令的控制器中工作,而不是链接?
MyDirective.ts:
module app.directives {
export class MyDirective {
priority = 0;
restrict = 'E';
templateUrl = 'template.html';
scope = {
'items': '='
};
controller = MyController;
link = MyLink;
static $inject = ['$timeout'];
constructor(private $timeout:ng.ITimeoutService) {
}
}
function MyController($scope:ng.IScope, $timeout:ng.ITimeoutService) {
console.log("controller", $timeout); // function timeout(fn,delay,invokeApply){ the guts here }
$timeout(function () {
console.log("This works fine");
},3000);
}
function MyLink(scope:ng.IScope, element:ng.IAugmentedJQuery, attr:ng.IAttributes, $timeout:ng.ITimeoutService) {
console.log("link to", $timeout); // MyController {}
$timeout(function () {
console.log("This throws the error, TypeError: $timeout is not a function");
},3000);
}
}
在directives.ts中连接它:
module app.directives {
angular.module('app').directive('MyDirective',['$timeout',($timeout:ng.ITimeoutService) => new MyDirective($timeout) ]);
}
app.ts
module app {
angular.module('app', []);
}
什么没用:
- 在 MyLink 中使用
this.$timeout,参数中包含或不包含$timeout。 - 我找到了几篇文章和示例,我试图确保我遵循我的应用程序中的逻辑,但似乎无法理解。
结语
- Typescript-Angular 仍然是新事物,还有很多最佳实践尚未定义。我团队项目的一部分是找到其中的一些。
- 我们一直在研究这个总体结构,所以除非有令人信服的理由,否则请不要建议我过多地改变所有结构。
【问题讨论】:
标签: javascript angularjs angularjs-directive typescript angular-directive