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

时间:2015-04-16 06:25:20

标签: angularjs typescript

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

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

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

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

我如何更改它以便它使用打字稿,所以即使我缩小了我的javascript后它也能正常工作?

1 个答案:

答案 0 :(得分:8)

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

我喜欢使用$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);