如果你使用 Angular1.5+ 可以遵循 Angular2 组件风格:
class DemoController implements ng.IComponentController {
public static $inject = [
'Service1',
];
constructor(private Service1: IService1) {
//
}
public $onInit(): void {
// ---
}
public $postLink(): void {
// ---
}
// ---
}
export const DemoComponent = {
selector: 'demoComponent',
bindings: {
prop1: '<',
prop2: '<',
},
controller: DemoController,
templateUrl: require('./your-tpl.html'),
};
在你的模块的某个地方,你可以注册这个组件:
.component(DemoComponent.selector, DemoComponent)
对于创建指令,这种代码风格也很不错:
export class MyDemoDirective implements ng.IDirective {
public restrict: string;
public static $inject: string[] = [
'Service1',
'Service2',
];
constructor(private Service1: IService1, private Service2: IService2) {
this.restrict = 'A';
// ---
}
public link(...) {
// ---
}
public static factory(): ng.IDirectiveFactory {
const directive = (Service1: IService1, Service2: IService2) => {
return new MyDemoDirective($filter, User);
};
return directive;
}
}