我有以下使用 TypeScript 编写的 AngularJS 应用程序
我初始化应用程序的主应用程序:
module MainApp {
export class App {
public static Module : ng.IModule = angular.module("mainApp", [])
}
}
还有我的 Controller
module MainApp {
export class Person {
public firstName: string;
public lastName: string;
}
export interface IMainAppCtrl {
}
export class MainAppCtrl implements IMainAppCtrl {
public person : Person;
constructor() {
this.person = new Person();
this.person.firstName = "Vorname";
this.person.lastName = "Nachname";
}
}
MainApp.App.Module.controller("mainAppCtrl", MainAppCtrl);
}
那行得通,但我对这个解决方案不是很满意,因为在这里我必须在我的 Controller 本身中为我的应用程序注册 Controller
MainApp.App.Module.controller("mainAppCtrl", MainAppCtrl);
如果可以直接在“App”类中注册 Controller 就好了:
public static Module : ng.IModule = angular.module("mainApp", []).controller("mainAppCtrl", MainAppCtrl);
但是那在这里不起作用我从浏览器收到错误消息
“参数‘mainAppCtrl’不是函数,未定义”
在我旧的纯 JS Angular Controller 中,我有一个 mainApp,我在其中注册了我所有的 Controller
angular.module("app.main", [
"ui.router",
"ngSanitize",
"DirectiveTestsCtrl",
....
]);
在我的 Controller 中,我只注册了 angular 的 Controller 名称:
angular.module("DirectiveTestsCtrl", [])
.controller("DirectiveTestsCtrl", function () { ... });
这是否也可以用上面显示的带有 typescript 的狙击手或这里的最佳实践 - 我在网上搜索并找到了很多例子,但对于 controlerAs 语法和“module Name {class xyz}”来说不是一个好的例子真的很有效。
最佳答案
TLDR; - Export a static function on your main module that will handle all the bootstrapping/initialization logic. For child/sub modules export a static readonly property which will allow you to build once and retrieve multiple times a defined angular module.
主模块
我采用了类似的方法,但它至少将额外的组件( Controller 、服务)封装在模块定义中
module appName {
export class App {
static createModule(angular: ng.IAngularStatic) {
angular.module('moduleName', ['ngRoute'])
.controller('refCtrl', ReferencedControllerClass)
.service('dataService', DataService);
}
}
}
appName.App.createModule(angular);
子模块
然后在其他内部模块中,我创建了一个对该模块的静态引用,以说明它被多次引用...
module appName {
export class SubModuleName {
private static _module:ng.IModule;
public static get module():ng.IModule {
if (this._module) {
return this._module;
}
this._module = angular.module('subModuleName', []);
this._module.controller('SomeCtrl', SomeController);
return this._module;
}
}
}
通过这种方法,我可以通过以下方式将我的 SubModule 注入(inject)到主 Angular 模块中:
angular.module('moduleName', ['ngRoute', appName.SubModuleName.module.name])
注意:为了保持一致性,主模块可以定义为子模块,但我只引用/构建它一次,所以我没有费心用本地静态实例缓存它。
关于javascript - 如何初始化 - 使用 TypeScript 的 AngularJs 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29545246/