我知道一种方法是将 Controller 对象附加到作用域,如下所示。
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
}
}
在这种情况下, View 将是这样的,
<div ng-controller="InfoCtrl">
<div class="rm-dialog-header">{{info.header}}</div>
<span ng-click="info.getData()">{{info.name}}</span>
</div>
除了上述之外,还有一种方法可以公开 Controller ,这样我就不必在每个作用域变量前添加“info.”前缀。这样 View 就会像这样,
<div ng-controller="InfoCtrl">
<div class="rm-dialog-header">{{header}}</div>
<span ng-click="getData()">{{name}}</span>
</div>
有可能吗,还是我错过了什么?
最佳答案
您可以直接在 $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
}
}
然后在您的标记中,您可以直接绑定(bind)到 getData()
只需确保使用语法 method = () => {}
声明您的方法,这会将方法放在实例上而不是原型(prototype)上。
关于angularjs - 使用 typescript 时公开 AngularJS Controller 方法的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30527112/