Typescript 中的 Angualr 控制器

如 AngularJS 文档中所定义

当 Controller 通过 ng-controller 指令附加到 DOM 时,Angular 将使用指定的 Controller 的构造函数实例化一个新的 Controller 对象。将创建一个新的子作用域,并将其作为$ scope 作为 Controller 的构造函数的可注入参数。

使用 typescript 类可以非常容易地制作控制器。

module App.Controllers {
    class Address {
        line1: string;
        line2: string;
        city: string;
        state: string;
    }
    export class SampleController {
        firstName: string;
        lastName: string;
        age: number;
        address: Address;
        setUpWatches($scope: ng.IScope): void {
            $scope.$watch(() => this.firstName, (n, o) => {
                //n is string and so is o
            });
        };
        constructor($scope: ng.IScope) {
            this.setUpWatches($scope);
        }
    }
}

结果是 Javascript

var App;
(function (App) {
    var Controllers;
    (function (Controllers) {
        var Address = (function () {
            function Address() {
            }
            return Address;
        }());
        var SampleController = (function () {
            function SampleController($scope) {
                this.setUpWatches($scope);
            }
            SampleController.prototype.setUpWatches = function ($scope) {
                var _this = this;
                $scope.$watch(function () { return _this.firstName; }, function (n, o) {
                    //n is string and so is o
                });
            };
            ;
            return SampleController;
        }());
        Controllers.SampleController = SampleController;
    })(Controllers = App.Controllers || (App.Controllers = {}));
})(App || (App = {}));
//# sourceMappingURL=ExampleController.js.map

在制作控制器类之后,通过使用类可以简单地完成关于控制器的角度 js 模块

app
 .module('app')
 .controller('exampleController', App.Controller.SampleController)