[英]extending $scope while converting directive to typescript
i want to convert existing directive in javascript to typescript. 我想将javascript中的现有指令转换为打字稿。 How do i convert below function
我如何转换以下功能
$scope.loadData = function () {
$scope.tableParams = $cspagination.initPromise(getPagedData);
};
So I am trying to write it as 所以我想写成
class controller {
this $scope.loadData = (): void {
.....
.....
};
}
but it is giving error that this is not available on class level. 但是这给出了错误,它在类级别不可用。 then i tried
然后我尝试了
class controller {
public $scope.loadData = (): void {
.....
.....
};
}
but this also does not work. 但这也不起作用。 its obvious that I cannot define a new public property on $scope, but then atleast I should be able to assign value to it.
很明显,我无法在$ scope上定义新的公共属性,但是至少我应该能够为其分配值。
so how do I dynamically add functions on $scope?? 那么如何在$ scope上动态添加函数呢? The workaround I could think of is creating a function
extendScope
and then 我能想到的解决方法是创建一个函数
extendScope
,然后
class controller {
public loadData = (): void => {
.....
.....
};
private extendScope = (): void =>{
this.$scope.loadData = this.loaddata;
}
constructor(){
this.extendScope();
}
}
but then this feels like a hack.. are there any cleaner ways of doing this? 但这感觉就像是骇客。.有没有更清洁的方法?
The way I go - is to create custom scope definition (ie inteface) , eg: 我的方式-创建自定义范围定义 (即接口) ,例如:
export interface IMyScope extends ng.IScope
{
loadData: () => void;
otherFunction: function;
...
Ctrl: MyCtrl;
}
and Controller constructor now requires that interface 现在,Controller构造函数需要该接口
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 => {
//.....
}
See more here: 在这里查看更多:
I don't see anything wrong with this, only that your loadData
method shouldn't be public in this case. 我没有发现任何问题,只是在这种情况下您的
loadData
方法不应该公开。 What I would do though is use the 'controller-as' method: 我要做的是使用“ controller-as”方法:
class controller {
static ID = "myController";
// defining methods like this will make them immediately available on
// the controller with the 'controller as' method
public loadData = (): void => {
//.....
}
constructor(){
}
}
And in your html: 并在您的html中:
<div ng-controller="myController as $my">
<button ng-click="$my.loadData()">Load!</button>
</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.