如何使用打字稿在 gulp-angular-generator 中定义指令

How to define a directive in gulp-angular-generator using typescript

我正在使用 Yeoman 生成器 gulp-angular-generator 使用 Typescript 创建一个 Angular 1.3 项目。种子项目展示了如何创建控制器而不是指令。到目前为止,这是我失败的尝试:

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 中定义整个指令,就像定义控制器一样(如 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
    };
  }
}

在此处详细了解如何在打字稿中编写指令:http://blog.aaronholmes.net/writing-angularjs-directives-as-typescript-classes/