entre entre - 3 months ago 16
TypeScript Question

extending $scope while converting directive to typescript

i want to convert existing directive in javascript to typescript. 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.

so how do I dynamically add functions on $scope?? The workaround I could think of is creating a function
extendScope
and then

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?

Answer

The way I go - is to create custom scope definition (i.e. inteface), e.g.:

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

and Controller constructor now requires that 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 => {
       //.....
    }

See more here: