我正在使用 Yeoman 生成器 gulp-angular-generator使用 Typescript 创建 Angular 1.3 项目。种子项目展示了如何创建 Controller 而不是指令。这是我迄今为止失败的尝试:
src/app/index.ts
/// <reference path="../../.tmp/typings/tsd.d.ts" />
/// <reference path="components/workspace/workspace.controller.ts" />
/// <reference path="components/dashboard/dashboard.directive.ts" />
module app {
'use strict';
angular.module('app', ['ngAnimate', 'ngCookies', 'ngTouch', 'ngSanitize', 'restangular', 'ngRoute', 'ui.bootstrap'])
.controller('WorkspaceCtrl', WorkspaceCtrl)
.config(function ($routeProvider: ng.route.IRouteProvider) {
$routeProvider
.when('/', {
templateUrl: 'app/components/workspace/workspace.template.html',
controller: 'WorkspaceCtrl',
controllerAs: 'workspace'
})
.otherwise({
redirectTo: '/'
});
});
}
src/app/components/workspace/workspace.controller.ts
module app {
'use strict';
export class WorkspaceCtrl {
//some code..
}
}
src/app/components/dashboard/dashboard.directive.ts
module app {
'use strict';
angular
.module('app')
.directive('dashboard', () => {
return {
restrict: 'E',
controllerAs: 'dashboard',
bindToController: true,
scope: {},
templateUrl: 'app/components/dashboard/dashboard.template.html',
controller: DashboardCtrl
};
});
class DashboardCtrl {
//some code..
}
}
当我尝试运行此代码时,我在浏览器控制台 (Chrome) 上收到以下错误:
Uncaught Error: [$injector:nomod] Module 'app' is not available! You either
misspelled the module name or forgot to load it. If registering a module ensure
that you specify the dependencies as the second argument.
检查浏览器源文件,我意识到指令文件是在模块定义所在的索引之前加载的。
我知道我可以在 index.ts
中定义整个指令,就像定义 Controller 一样(如 gulp-generator 所建议的那样),但这不是一个好主意,因为指令定义对象 (DDO) 通常很大,一旦您的应用开始增长,维护就会变得更加困难。
有没有办法在不同的文件中定义指令并指示生成器以正确的顺序加载文件?
最佳答案
试试这个
module app {
'use strict';
export function dashboard(): ng.IDirective {
return {
restrict: 'E',
controllerAs: 'dashboard',
bindToController: true,
scope: {},
templateUrl: 'app/components/dashboard/dashboard.template.html',
controller: DashboardCtrl
};
}
}
在此处阅读有关如何在 typescript 中编写指令的更多信息:http://blog.aaronholmes.net/writing-angularjs-directives-as-typescript-classes/
关于angularjs - 如何使用 typescript 在 gulp-angular-generator 中定义指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30107996/