如何将 AngularJS Javascript 控制器转换为 Typescript?

How can I convert an AngularJS Javascript controller to Typescript?

我有一个非常简单的控制器:

.controller('ModalInstanceCtrl', function ($scope, $modalInstance, $userService) {

        $scope.ok = function () {
            $modalInstance.close();
        };

        $scope.cancel = function () {
            $modalInstance.dismiss('cancel');
        };
    })

我怎样才能改变它,让它使用打字稿,这样即使在我缩小 javascript 之后它也能正常工作?

控制器和服务可以变成 类。

我喜欢使用 $inject,所以缩小是安全的,但该行是可选的。

class ModalInstanceController {
    static $inject = ["$scope", "$modalInstance", "$userService"];
    constructor($scope, $modalInstance, $userService) {

        $scope.ok = () => {
            $modalInstance.close();
        };

        $scope.cancel = () => {
            $modalInstance.dismiss('cancel');
        };
    }
}
.controller('ModalInstanceCtrl', ModalInstanceController);

包括 $inject 等同于使用 vanilla 中的数组语法 JavaScript:

.controller('ModalInstanceCtrl', ["$scope", "$modalInstance", "$userService", function ($scope, $modalInstance, $userService) { ... }]);

在现实世界的应用程序中,我喜欢避免使用 $scope 除了实际需要它的东西(比如 $watch),在这种情况下我会把方法拿出来以及。不过,这需要更改您的 HTML。

class ModalInstanceController {
    private $modalInstance : any;

    static $inject = ["$modalInstance", "$userService"];
    constructor($modalInstance, $userService) {
        this.$modalInstance = $modalInstance;
    }

    ok() {
        this.$modalInstance.close();
    }
    cancel() {
        this.$modalInstance.dismiss('cancel');
    };
}

然后在你的 HTML,

<button type="button" ng-click="ModalInstanceCtrl.ok()">OK</button>

请注意完全限定 ModalInstanceCtrl.ok() 的使用,因为它不再只是在范围内浮动。


自从你在我无聊的时候抓住了我,这是使用 TypeScript 的一个很好的优势,因为我看到你有 $userService

class UserService {
    // A parameterized constructor is, of course, allowed here too.
    // Optionally supply $inject, per above

    parse(arg : string) {
        return parseInt(arg);
    }
}

class ModalInstanceController {
    private $modalInstance : any;
    private $userService : UserService; // Note the typing here

    static $inject = ["$modalInstance", "$userService"];
    // Explicit typing here is optional, since "any" will cast automatically
    // but I like to be clear anyway.
    constructor($modalInstance, $userService : UserService) {
        this.$modalInstance = $modalInstance;
        this.$userService = $userService;
    }

    ok() {
        // you'll get Intellisense here, whilst still benefiting from DI from Angular
        var arg = this.$userService.parse("12");

        this.$modalInstance.close();
    }
    cancel() {
        this.$modalInstance.dismiss('cancel');
    };
}
app.service("$userService", UserService);
app.controller("ModalInstanceCtrl", ModalInstanceController);