AngularJS Typescript中的角度控制器

示例

如AngularJS文档中所定义

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

使用打字稿类可以很容易地制作控制器。

moduleApp.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是字符串,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是字符串,o也是如此
                });
            };
            ;
            return SampleController;
        }());
       Controllers.SampleController= SampleController;
    })(Controllers =App.Controllers|| (App.Controllers = {}));
})(App || (App = {}));
//#sourceMappingURL = ExampleController.js.map

在制作好控制器类之后,可以通过使用该类来简化关于控制器的Angular js模块

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