【问题标题】:Has anyone tried using typescript enums in AngularJS HTML pages?有没有人尝试在 AngularJS HTML 页面中使用 typescript 枚举?
【发布时间】:2014-10-18 05:52:26
【问题描述】:

在 Typescript 中,我创建了一个这样的枚举:

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

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

class AuthService implements IAuthService {

    action: number;

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

        this.action = Action.None;

    }

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

这很好用,但我如何在我的 HTML 中使用枚举。那可能吗?我想做的是在这样的地方使用它:

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

无需为以下各项创建不同的变量:

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

【问题讨论】:

    标签: angularjs typescript


    【解决方案1】:

    你可以把它放在$rootScope 例如

    mainmodule.run([
        '$rootScope'
    ], function ($rootScope){
    
        // put it on $rootScope
        $rootScope.Action = Action;
    });
    

    由于每个$scope 都继承自它,因此它位于每个作用域上,您只需执行Action.foo 等。

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

    【讨论】:

    • 我也一直在检查常量的使用。您认为使用 app.constant( 还是使用 Typescript 解决方案更容易?
    • 你能告诉我如何将 $rootScope 注入控制器吗?我是注入 $rootScope 还是只注入 $scope?
    • 两者。但你不需要。像任何其他不需要访问角度的 ts 实用函数一样使用枚举
    猜你喜欢
    • 1970-01-01
    • 2015-10-20
    • 1970-01-01
    • 1970-01-01
    • 2021-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多