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?

1
  • 1
    Before you'll get your answer, here is how I use it with a working plunker Commented May 29, 2015 at 10:22

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Please read 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.