gpt4 book ai didi

angularjs - 在 Typescript 中将 angularjs 指令实现为类

转载 作者:搜寻专家 更新时间:2023-10-30 20:31:32 25 4
gpt4 key购买 nike

所以在看了一些 angularjs 指令在 typescript 中的例子之后,似乎大多数人都同意在实现它们时使用函数而不是类。

我更愿意将它们作为一个类并尝试按如下方式实现它们:

module directives
{
export class search implements ng.IDirective
{
public restrict: string;
public templateUrl: string;

constructor()
{
this.restrict = 'AE';
this.templateUrl = 'directives/search.html';
}

public link($scope: ng.IScope, element: JQuery, attributes: ng.IAttributes)
{
element.text("Hello world");

}
}
}

现在一切正常。但是,我需要一个具有某些属性的隔离范围,并且我正在努力寻找如何将其包含在类本身中。

逻辑决定了既然我可以拥有

public restrict: string;
public templateUrl: string;

我应该能够拥有类似的东西:

public scope;

但我不确定这是否正确或如何从那里继续(即如何将属性添加到范围)。

有人知道怎么解决吗? (希望,如果可能的话,不必恢复到一个功能)

谢谢,

最佳答案

将指令创建为类可能会出现问题,因为您仍然需要涉及工厂函数来包装其实例化。例如:

export class SomeDirective implements ng.IDirective {
public link = () => {
}

constructor() {}
}

什么不起作用

myModule.directive('someDirective', SomeDirective);

因为指令不是使用“new”调用的,而只是作为工厂函数调用的。这将导致您的构造函数实际返回的内容出现问题。

有什么作用(有注意事项)

myModule.directive(() => new SomeDirective());

如果您不涉及任何 IoC,这会很好地工作,但是一旦您开始引入可注入(inject)程序,您就必须为您的工厂函数和指令构造函数维护重复的参数列表。

export class SomeDirective implements ng.IDirective {
...
constructor(someService: any) {}
}

myModule.directive('someDirective', ['someService', (someService) => new SomeDirective(someService)]);

如果您愿意,这仍然是一个选项,但对于了解指令注册的实际使用方式很重要。

另一种方法

angular 实际期望的是一个指令工厂函数,所以像这样:

export var SomeDirectiveFactory = (someService: any): ng.IDirective => {
return {
link: () => {...}
};
}
SomeDirectiveFactory.$inject = ['someService']; //including $inject annotations

myModule.directive('someDirective', SomeDirectiveFactory);

这具有允许使用 $inject 注释的好处,因为在这种情况下 Angular 需要它在工厂函数上。

你总是可以从工厂函数中返回你的类的一个实例:

export var SomeDirectiveFactory = (someService: any): ng.IDirective => {
return new SomeDirective(someService);
}
SomeDirectiveFactory.$inject = ['someService']; //including $inject annotations

但实际上取决于您的用例,您可以接受多少重复的参数列表等。

关于angularjs - 在 Typescript 中将 angularjs 指令实现为类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23535994/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com