2

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?

Baga
  • 1,354
  • 13
  • 24

1 Answers1

2

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.

Ross Scott
  • 1,690
  • 9
  • 16
  • 2
    Please read [Y030](https://github.com/johnpapa/angular-styleguide#style-y030) onwards in the Angular style guide and use `controller as` instead. `$scope` is really a deprecated concepts now, especially if you want to migrate to Angular 2 in the future. – billc.cn May 29 '15 at 15:47