Angularjs 在Angular/typescript中将静态变量(超出范围)绑定到html
我创建了一个小的TestTypeScript/angularjs网站 我有一个带有静态变量的模块,我想将其绑定到html文档,以便查看当前登录的用户Angularjs 在Angular/typescript中将静态变量(超出范围)绑定到html,angularjs,typescript,Angularjs,Typescript,我创建了一个小的TestTypeScript/angularjs网站 我有一个带有静态变量的模块,我想将其绑定到html文档,以便查看当前登录的用户 module mytest.constants { export class CurrentSession { public static CURRENT_USER: string = "Tobi"; } } 问题是: 当前作用域是与我的CurrentSession类分离的控制器 我想做一些像 以以下身份登
module mytest.constants {
export class CurrentSession {
public static CURRENT_USER: string = "Tobi";
}
}
问题是:
当前作用域是与我的CurrentSession类分离的控制器
我想做一些像
以以下身份登录:{{mytest.constants.CurrentSession.CURRENT_USER}
我可以做的另一种方法是向控制器添加一个类成员,并在构造函数中设置它,如:
this.CurrentUSer = mytest.constants.CurrentSession.CURRENT_USER
但是我更愿意将静态变量直接绑定到html文件
这可能吗?您不能像这样绑定静态属性,Angular只是在其摘要周期中不检查这些属性。但是,您可以创建一个作用域/这个类本身的引用。大概是这样的:
module mytest.constants {
export class CurrentSession {
public static CURRENT_USER: string = "Tobi";
CurrentSession = CurrentSession;
}
}
export class MainCtrl {
public static $inject = ["$state", "$http", "CurrentSession"];
constructor($state, $http, private CurrentSession) {
...
}
因此,基本上它将创建自己的属性,如this.CurrentSession=CurrentSession
然后在模板中(假设您正在使用controllerAs语法和会话
参考控制器实例),您将能够将当前用户
绑定为
{{session.CurrentSession.CURRENT_USER}
感谢dfsq的快速回答
我终于找到了另一个解决办法
我首先在app.ts中设置一个名为“CurrentSession”的变量,并将该值设置为对象的一个新实例
angular.module("app", [])
.constant("CurrentSession", new mytest.constants.CurrentSession())
然后我可以像这样在我的控制器中注入这个常数:
module mytest.constants {
export class CurrentSession {
public static CURRENT_USER: string = "Tobi";
CurrentSession = CurrentSession;
}
}
export class MainCtrl {
public static $inject = ["$state", "$http", "CurrentSession"];
constructor($state, $http, private CurrentSession) {
...
}
这里的好处是,我可以使用“private CurrentSession”,它将自动设置一个成员变量“CurrentSession”
html如下所示:
module mytest.constants {
export class CurrentSession {
public static CURRENT_USER: string = "Tobi";
CurrentSession = CurrentSession;
}
}
export class MainCtrl {
public static $inject = ["$state", "$http", "CurrentSession"];
constructor($state, $http, private CurrentSession) {
...
}
注销{{main.CurrentSession.CURRENT_USER.Name}