use*_*899 17 angularjs typescript
因此,在看一下typescript中的angularjs指令的一些例子之后,似乎大多数人同意在实现它们时使用函数而不是类.
我更愿意将它们作为一个类,并尝试按如下方式实现它们:
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");
}
}
}
Run Code Online (Sandbox Code Playgroud)
现在这很好用.但是,我需要有一个具有某些属性的独立范围,我正在努力找出如何在类本身中包含它.
逻辑决定了我可以拥有
public restrict: string;
public templateUrl: string;
Run Code Online (Sandbox Code Playgroud)
我应该有类似的东西:
public scope;
Run Code Online (Sandbox Code Playgroud)
但我不确定这是否正确或如何从那里继续(即如何将属性添加到范围).
谁知道怎么解决这个问题?(希望如果可能的话,不必恢复功能)
谢谢,
bin*_*les 23
创建指令作为类可能会有问题,因为您仍需要使用工厂函数来包装其实例化.例如:
export class SomeDirective implements ng.IDirective {
public link = () => {
}
constructor() {}
}
Run Code Online (Sandbox Code Playgroud)
什么行不通
myModule.directive('someDirective', SomeDirective);
Run Code Online (Sandbox Code Playgroud)
因为指令不是使用'new'调用的,而只是作为工厂函数调用.这将导致构造函数实际返回的问题.
什么(有警告)
myModule.directive(() => new SomeDirective());
Run Code Online (Sandbox Code Playgroud)
如果您没有涉及任何IoC,这样可以正常工作,但是一旦开始引入注射剂,您必须为工厂函数和指令构造函数维护重复的参数列表.
export class SomeDirective implements ng.IDirective {
...
constructor(someService: any) {}
}
myModule.directive('someDirective', ['someService', (someService) => new SomeDirective(someService)]);
Run Code Online (Sandbox Code Playgroud)
如果这是您喜欢的选项,仍然是一个选项,但了解如何实际使用指令注册非常重要.
另一种方法
angular实际上预期的是一个指令工厂函数,所以类似于:
export var SomeDirectiveFactory = (someService: any): ng.IDirective => {
return {
link: () => {...}
};
}
SomeDirectiveFactory.$inject = ['someService']; //including $inject annotations
myModule.directive('someDirective', SomeDirectiveFactory);
Run Code Online (Sandbox Code Playgroud)
这有利于允许使用$ inject注释,因为在这种情况下,角度需要它在工厂函数上.
您始终可以从工厂函数返回类的实例:
export var SomeDirectiveFactory = (someService: any): ng.IDirective => {
return new SomeDirective(someService);
}
SomeDirectiveFactory.$inject = ['someService']; //including $inject annotations
Run Code Online (Sandbox Code Playgroud)
但实际上取决于您的使用案例,您可以使用多少参数列表重复等等.
bas*_*rat 20
假设您在没有islolated范围的情况下工作,则以下内容应与隔离范围一起使用:
module directives
{
export class search implements ng.IDirective
{
public restrict = 'AE';
public templateUrl = 'directives/search.html';
public scope = {
foo:'=',
bar:'@',
bas:'&'
};
public link($scope: ng.IScope, element: JQuery, attributes: ng.IAttributes)
{
element.text("Hello world");
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18531 次 |
| 最近记录: |