使用AngularJS和TypeScript以简单的方式引用

Referencing in a simple way using AngularJS and TypeScript

本文关键字:方式 引用 简单 AngularJS TypeScript 使用      更新时间:2023-09-26

我将VS2015与Gulp一起使用,并尝试使用TypeScript构建AngularJS。

在我的index.html中,我的"app.js"(TS构建的输出和捆绑包)有一个脚本标记。

但是,如果我想引用我的控制器和任何其他服务——我如何才能避免在每个HTML文件中放置相关的脚本标记——有没有一种方法可以直接引用app.js文件并完成它?推荐的方法是什么?

干杯,

如果你想通过script标记在html中只引用一个文件,而其他文件只是在其他js文件中引用,那么你可以使用requirejs。这是一个加载脚本的好工具。在生产中,这是一个很好的方法来连接和缩小所有脚本,以减少请求数量。

我用experimental typescript decoratorsrequirejs和一点想象力解决了这个问题。

所以,在简历中,我写了两个修饰词,一个叫AppStartup,另一个叫DependsOn。所以在angular bootstrap中,我可以获取并注册所有依赖项。

我最终得到了类似的东西:


TodoListController.ts

import {DependsOn, AppStartup, ngControllerBase} from "../infra/core";
import {taskManagerDirective} from "../directives/TaskManagerDirective";
@AppStartup({
    Name: "TodoSample"
}).Controller({
    DependsOn: [taskManagerDirective]
})
export class TodoListController extends ngControllerBase {
    public ByControllerAs: string;
    constructor() {
        super(arguments);
        let $httpPromise = this.$get<ng.IHttpService>("$http");
        $httpPromise.then(function ($http) {
            $http.get('http://www.google.com').success(function (body) {
                console.info("google.com downloaded, source code: ", body);
            });
        });
        this.ByControllerAs = "This was included by controllerAs 'this'";
    }
}

rowListItemDirective.ts

import {DependsOn, ngDirectiveBase} from "../infra/core";
import {rowListItemDirective} from "./RowListItemDirective";
@DependsOn([rowListItemDirective])
export class taskManagerDirective extends ngDirectiveBase{
    public template: string = `
    Parent Directive
        <table>
            <tbody>
                <tr row-list-item-directive></tr>
            </tbody>
        </table>
   `;
}

你可以在我的github存储库中看到我在下面做了什么:

https://github.com/klaygomes/angular-typescript-jasmine-seed