I am trying to create some Directives in Typescript using the pattern below. The problem is the block returned by 'compile' does not seem to get called. The class is definitely getting created and if I step through, I can see the compile function seems to get picked up when it's instantiated, but the code inside compile never runs.
I tried stripping down compile to a very simple call (i.e. compile (): any => { console.log('works') } and a few similar variations), but can't get any code in there to execute.
Any ideas?
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;
}
}
Update I did not originally include the code where I registered the directive with Angular, which looked like this:
angular.module('myModule').directive('myDirective', myDirective.factory);
Thanks to the hint from @Gustav, I realized the factory method registered with the Directive was returning a function. I needed to return the result of the factory function, so simply adding the parens to the call to the factory method did the trick:
angular.module('myModule').directive('myDirective', myDirective.factory());
directive- function you're returning in thefactory()-function?return directive()or just:return new myDirective()in the factory function, I think it might work. But again, I would suggest writing direcitves according to the structure of the link I posted before