似乎在组合TS和角度时,我在控制器上的所有内容都会暴露在视图中。就我而言,myPrivate
上会显示$ctrl
。
class MyController extends BaseController implements SomeInterface {
private myPrivate: string = 'myPrivateString';
}
是否有解决此问题的方法?
答案 0 :(得分:1)
为什么当你看到生成的javascript时,这是非常明显的。
var MyController = (function (_super) {
__extends(MyController, _super);
function MyController() {
_super.apply(this, arguments);
this.myPrivate = 'myPrivateString';
}
return MyController;
}(BaseController));
您的私人财产最终与控制器上的任何其他财产一样。
您可以看到完整的转化here。
一个解决方案是让一个参数化的基本控制器能够为视图设置类似于视图模型的东西,而不是普通的$ ctrl。
它看起来像这样:
class BaseController<T> {
protected scope;
protected viewModel: T;
constructor(scope: any, modelType: { new (): T; }) {
this.scope = scope;
this.viewModel = new modelType();
this.scope["viewModel"] = this.viewModel;
}
}
class MyParticularViewModel {
public somethingForTheView: string;
}
class MyController extends BaseController<MyParticularViewModel> implements SomeInterface {
private myPrivate: string = 'myPrivateString';
constructor(scope) {
super(scope, MyParticularViewModel);
}
}
在视图中,您可以使用 viewModel 属性访问所需的属性。
我在一个项目中已经将它用于实践中并且效果非常好。您可以看到我使用here的初学者模板获取更多信息。