使用typescript时公开angularjs控制器方法的最佳方法?
我理解这样做的一种方法是将控制器对象附加到作用域,如下所示使用typescript时公开angularjs控制器方法的最佳方法?,angularjs,typescript,Angularjs,Typescript,我理解这样做的一种方法是将控制器对象附加到作用域,如下所示 interface IAppCtrlScope extends ng.IScope { info: any; } class InfoCtrl { header: string; name: string; public static $inject = ["$scope"]; constructor(private $scope: IAppCtrlScope) {
interface IAppCtrlScope extends ng.IScope {
info: any;
}
class InfoCtrl {
header: string;
name: string;
public static $inject = ["$scope"];
constructor(private $scope: IAppCtrlScope) {
this.$scope.info= this; //expose controller
}
getData(): void {
//do something
}
}
在这种情况下,视图将是这样的
<div ng-controller="InfoCtrl">
<div class="rm-dialog-header">{{info.header}}</div>
<span ng-click="info.getData()">{{info.name}}</span>
</div>
<div ng-controller="InfoCtrl">
<div class="rm-dialog-header">{{header}}</div>
<span ng-click="getData()">{{name}}</span>
</div>
{{info.header}
{{info.name}
除了上面提到的,还有一种公开控制器的方法,这样我就不必在每个作用域变量前面加上'info'。这样的景色就是这样的,
<div ng-controller="InfoCtrl">
<div class="rm-dialog-header">{{info.header}}</div>
<span ng-click="info.getData()">{{info.name}}</span>
</div>
<div ng-controller="InfoCtrl">
<div class="rm-dialog-header">{{header}}</div>
<span ng-click="getData()">{{name}}</span>
</div>
{{header}}
{{name}}
有没有可能或者我遗漏了什么 您可以直接在$scope上公开类中的方法
interface IAppCtrlScope extends ng.IScope {
getData: () => void;
}
class InfoCtrl {
header: string;
name: string;
public static $inject = ["$scope"];
constructor(private $scope: IAppCtrlScope) {
$scope.getData = this.getData; //expose method
}
getData = () => {
//do something
}
}
然后在标记中可以直接绑定到getData()
只需确保使用语法
method=()=>{}
声明方法,这会将方法放在实例而不是原型上。在您得到答案之前,我是如何将其与工作实例一起使用的plunker@RadimKöhler,谢谢你的链接,非常有用!请阅读《角度样式指南》中的后续内容,并改用控制器作为
$scope
现在确实是一个不推荐使用的概念,特别是如果您希望将来迁移到Angular 2。