Baga
Baga

Reputation: 1452

Best way to expose angularjs controller methods when using typescript?

I understand one way of doing it is attaching the controller object to the scope like below.

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
    }    
}

In this case the view will be something like this,

<div ng-controller="InfoCtrl">
    <div class="rm-dialog-header">{{info.header}}</div>
    <span ng-click="info.getData()">{{info.name}}</span>
</div>

Instead of the above is there a way to expose the controllers so that I dont have to prefix each scope variable with 'info.'. So that the view will be like this,

<div ng-controller="InfoCtrl">
    <div class="rm-dialog-header">{{header}}</div>
    <span ng-click="getData()">{{name}}</span>
</div>

Is it possible or am I missing something?

Upvotes: 2

Views: 1069

Answers (1)

Ross Scott
Ross Scott

Reputation: 1732

You can expose methods from your class directly on the $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
    }    
}

then in you markup you can bind directly to getData()

Just make sure you declare your method using the syntax method = () => {}, this places the method on the instance rather than the prototype.

Upvotes: 2

Related Questions