Tob*_*ler 5 angularjs typescript
我创建了一个小测试typescript/angularjs网站.
我有一个静态变量的模块,我想绑定到html文档,以便我可以看到当前登录的用户.
module mytest.constants {
export class CurrentSession {
public static CURRENT_USER: string = "Tobi";
}
}
Run Code Online (Sandbox Code Playgroud)
问题是:当前作用域是一个与我的CurrentSession类分开的控制器.
我想做点什么
<div class="label" style="color:green">
Logged in as: {{mytest.constants.CurrentSession.CURRENT_USER}}
</div>
Run Code Online (Sandbox Code Playgroud)
我可以做的另一种方法是将一个类成员添加到控制器并在构造函数中设置它:
this.CurrentUSer = mytest.constants.CurrentSession.CURRENT_USER
Run Code Online (Sandbox Code Playgroud)
但我更喜欢将静态变量直接绑定到html文件.
这可能吗?
你不能像这样绑定静态属性,Angular只是不检查它的摘要周期.但是,您可以为类本身创建范围/此引用.像这样的东西:
module mytest.constants {
export class CurrentSession {
public static CURRENT_USER: string = "Tobi";
CurrentSession = CurrentSession;
}
}
Run Code Online (Sandbox Code Playgroud)
所以基本上它会创建自己的属性this.CurrentSession = CurrentSession.
然后在模板中(假设您正在使用controllerAs语法并session参考控制器实例),您将能够绑定CURRENT_USER为
<div>{{session.CurrentSession.CURRENT_USER}}</div>
Run Code Online (Sandbox Code Playgroud)
感谢 dfsq 的快速答复。
我终于找到了另一个解决方案。
我首先在 app.ts 中设置一个名为“CurrentSession”的变量,并将该值设置为对象的新实例
angular.module("app", [])
.constant("CurrentSession", new mytest.constants.CurrentSession())
Run Code Online (Sandbox Code Playgroud)
然后我可以像这样在我的控制器中注入这个常量:
export class MainCtrl {
public static $inject = ["$state", "$http", "CurrentSession"];
constructor($state, $http, private CurrentSession) {
...
}
Run Code Online (Sandbox Code Playgroud)
这里的好处是,我可以使用“私有 CurrentSession”,它将自动设置成员变量“CurrentSession”。
html 看起来像这样:
angular.module("app", [])
.constant("CurrentSession", new mytest.constants.CurrentSession())
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6688 次 |
| 最近记录: |