有人尝试过在AngularJS HTML页面中使用打字稿枚举吗?

时间:2022-09-25 23:22:11

In Typescript I created an enum like this:

在打字稿中,我创建了这样一个enum:

enum Action { None = 0, Registering = 1, Authenticating = 2 };

In my controller I set a property called action like this:

在我的控制器中,我设置了一个名为action的属性,如下所示:

class AuthService implements IAuthService {

    action: number;

    constructor(
        private $state,
        private userService,
        private utilityService: IUtilityService
        ) {

        this.action = Action.None;

    }

    doRegister() => {
       this.action = Action.Registering;
    }

This works good but how can I use the enum in my HTML. Is that possible? What I would like to do is to use it in some place like this:

这很好,但是我如何在HTML中使用enum呢?这有可能吗?我想做的是在这样的地方使用它:

<span ng-class="{'fa-spin fa-spinner': app.authService.authenticating }">

Without the need to create different variables for:

不需要创建不同的变量:

app.authService.authenticating
app.authService.registering
...
etc

1 个解决方案

#1


11  

You can put that on the $rootScope e.g.

你可以把它放在$rootScope上。

mainmodule.run([
    '$rootScope'
], function ($rootScope){

    // put it on $rootScope
    $rootScope.Action = Action;
});

And since every $scope inherits from it it is on each scope and you can just do Action.foo etc.

因为每个$scope从它继承而来,它在每个范围上,你可以只做动作。foo等等。

Note: For directives with an isolate scope you need to do $root.Action.foo. Just Action would not work as it intentionally breaks the prototype chain.

注意:对于具有隔离范围的指令,需要执行$root.Action.foo。仅仅采取行动是行不通的,因为它故意破坏了原型链。

#1


11  

You can put that on the $rootScope e.g.

你可以把它放在$rootScope上。

mainmodule.run([
    '$rootScope'
], function ($rootScope){

    // put it on $rootScope
    $rootScope.Action = Action;
});

And since every $scope inherits from it it is on each scope and you can just do Action.foo etc.

因为每个$scope从它继承而来,它在每个范围上,你可以只做动作。foo等等。

Note: For directives with an isolate scope you need to do $root.Action.foo. Just Action would not work as it intentionally breaks the prototype chain.

注意:对于具有隔离范围的指令,需要执行$root.Action.foo。仅仅采取行动是行不通的,因为它故意破坏了原型链。