gpt4 book ai didi

javascript - 将指令转换为 typescript 时扩展 $scope

转载 作者:行者123 更新时间:2023-12-02 14:18:19 26 4
gpt4 key购买 nike

我想将 javascript 中的现有指令转换为 typescript。我如何转换下面的函数

    $scope.loadData = function () {
$scope.tableParams = $cspagination.initPromise(getPagedData);
};

所以我尝试将其写为

  class controller {
this $scope.loadData = (): void {
.....
.....
};
}

但它给出了错误,表明这在类级别上不可用。然后我尝试了

  class controller {
public $scope.loadData = (): void {
.....
.....
};
}

但这也行不通。很明显,我无法在 $scope 上定义新的公共(public)属性,但至少我应该能够为其赋值。

那么如何在 $scope 上动态添加函数?我能想到的解决方法是创建一个函数 extendScope 然后

   class controller {
public loadData = (): void => {
.....
.....
};

private extendScope = (): void =>{
this.$scope.loadData = this.loaddata;
}

constructor(){
this.extendScope();
}

}

但这感觉就像是一个黑客......有没有更干净的方法来做到这一点?

最佳答案

我的方法 - 是创建自定义范围定义(即界面),例如:

export interface IMyScope  extends ng.IScope
{
loadData: () => void;
otherFunction: function;
...
Ctrl: MyCtrl;
}

Controller 构造函数现在需要该接口(interface)

export class MyCtrl
{
static $inject = ["$scope", ...];
constructor(protected $scope: IMyScope ,
...)
{
this.$scope.Ctrl = this; // we can use "controllerAs" as well
// and here we can add these functions
this.$scope.loadData = this.loadData;
this.$scope.otherFunction = function() {};
...
}

public loadData = (): void => {
//.....
}

在此处查看更多内容:

关于javascript - 将指令转换为 typescript 时扩展 $scope,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38868131/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com