将静态变量(超出范围)绑定到Angular / typescript中的html

时间:2015-07-18 09:54:29

标签: angularjs typescript

我创建了一个小测试typescript / angularjs网站。

我有一个静态变量的模块,我想绑定到html文档,以便我可以看到当前登录的用户。

module mytest.constants {

    export class CurrentSession {

        public static CURRENT_USER: string = "Tobi";

    }
}

问题是: 当前作用域是一个与我的CurrentSession类分开的控制器。

我想做点什么

<div class="label" style="color:green">
  Logged in as: {{mytest.constants.CurrentSession.CURRENT_USER}}
</div>

我能做的另一种方法是将一个类成员添加到控制器并在构造函数中设置它:

this.CurrentUSer = mytest.constants.CurrentSession.CURRENT_USER

但我更喜欢将static-variable直接绑定到html文件。

这可能吗?

2 个答案:

答案 0 :(得分:6)

你不能像这样绑定静态属性,Angular不会在其摘要周期中检查那些。但是,您可以为类本身创建范围/此引用。像这样:

unless

所以基本上它会创建自己的属性,如module mytest.constants { export class CurrentSession { public static CURRENT_USER: string = "Tobi"; CurrentSession = CurrentSession; } }

然后在模板中(假设您使用带有this.CurrentSession = CurrentSession的controllerAs语法引用控制器实例),您将能够将session绑定为

CURRENT_USER

答案 1 :(得分:2)

谢谢dfsq的快速回答。

我终于找到了另一种解决方案。

我首先在app.ts中设置了一个名为“CurrentSession”的变量,并将值设置为我的对象的新实例

angular.module("app", [])
    .constant("CurrentSession", new mytest.constants.CurrentSession())

然后我可以像这样在我的控制器中注入这个Constant:

export class MainCtrl {

    public static $inject = ["$state", "$http", "CurrentSession"];

    constructor($state, $http, private CurrentSession) {
      ...
    }

这里的好处是,我可以使用“private CurrentSession”,它将自动设置成员变量“CurrentSession”。

html看起来像这样:

<button ng-click="main.logOut()">Log out {{main.CurrentSession.CURRENT_USER.Name}}</button>
相关问题