angularjs - angular/Typescript 指令 - compile 函数未被调用
我正在尝试使用下面的模式在 Typescript 中创建一些指令。问题是 'compile' 返回的代码块似乎没有被调用。类确实被创建了,如果我逐步调试,我可以看到当它被实例化时 compile 函数似乎被拾取了,但 compile 内部的代码从未运行。
我尝试将 compile 简化为一个非常简单的调用(即 compile(): any => { console.log('works') } 和一些类似的变体),但是无法让其中的任何代码执行。
有什么想法吗?
export class myDirective implements ng.IDirective {
public restrict: string = 'AE';
constructor() {
console.log('my-directive ctor'); // this message IS logged
}
public compile = (element: JQuery, attrs: ng.IAttributes, transclude: any): ng.IDirectivePrePost => {
element.addClass('my-directive-class');
console.log('in compile'); // this message IS NOT logged
return {
pre: ($scope: any, element: JQuery, attrs: ng.IAttributes) => {
console.log('in compile pre'); // this message IS NOT logged
},
post: ($scope: any, element: JQuery, attrs: ng.IAttributes) => {
console.log('in compile post'); // this message IS NOT logged
}
};
}
public static factory(): ng.IDirectiveFactory {
var directive = () => {
return new myDirective();
};
return directive;
}
}
更新 我最初没有包括我在 Angular 中注册指令的代码,看起来是这样的:
angular.module('myModule').directive('myDirective', myDirective.factory);
感谢 @Gustav 的提示,我意识到与 Directive 注册的工厂方法返回的是一个函数。我需要返回工厂函数的结果,所以只需在调用工厂方法时加上括号就可以了:
angular.module('myModule').directive('myDirective', myDirective.factory());