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)