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

3

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

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

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

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

我该如何更改代码以使用typescript,并使其在压缩JavaScript后仍然能够正常工作?


3
有效的JavaScript也是有效的TypeScript-恭喜,你做到了。 - Marty
@Marty,说得好。但是利用本地的TypeScript类功能等将其清理并使其在规模上更易于维护,还有其他一些优点。我这样说只是为了防止你的“不清楚”VTC-知道如何从TypeScript受益是很有好处的,因为你无论如何都会使用它。即使你不必这样做。 - Matthew Haugen
@MatthewHaugen 当然 - 我只是有点调皮。 - Marty
@Marty 好的,只是确认一下。 :) - Matthew Haugen
1个回答

9

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

我喜欢使用$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与使用原生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(),因为它不再仅仅漂浮在作用域中。
由于看到你有$userService,所以我来分享一下使用TypeScript的好处。
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);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接