0

I've seen a couple of examples of using TypeScript with an angular controller and attaching methods via the scope like this one.

However, it's now better practice to use controllerAs.

Given the following TypeScript (assuming it was correctly registered as a controller elsewhere etc.):

class exampleCtrl {

    public publicArray = [1,2,3];

    public somePublicMethod() {
        window.console.log('ran function')
    }

}

This produces:

var exampleCtrl = (function () {
    function exampleCtrl() {
        this.publicArray = [1, 2, 3];
    }
    exampleCtrl.prototype.somePublicMethod = function () {
        window.console.log('ran function');
    };
    return exampleCtrl;
}());

Notice how somePublicMethod has been added to the prototype, yet publicArray is added directly to this.

As far as I can tell, methods added to the prototype are not available via the DOM using controllerAs.

e.g

<div ng-controller="exampleCtrl as vm">
    {{vm}} <!-- No function is output just {"publicArray":[1,2,3]} -->
    <div ng-click="vm.somePublicMethod">Click me</div> <!-- click event doesn't work -->
</div>

How can I now access somePublicMethod via the DOM? Or rather, how can I make a public function in a TypeScript (ES6) class publicly accessible when using controllerAs syntax?

plunker to show what I am seeing.


Other points:

I know public, private and protected don't actually change the way the code is transpiled, it just warns you if you use it wrongly.

Community
  • 1
  • 1
Matt Lishman
  • 1,817
  • 2
  • 22
  • 34

1 Answers1

2

It is

<div ng-click="vm.somePublicMethod()">Click me</div>

As far as I can tell, methods added to the prototype are not available via the DOM using controllerAs.

They are. That's how JS prototypes work.

Estus Flask
  • 206,104
  • 70
  • 425
  • 565
  • Oh whoops, simple error when making an isolated example. I thought that was the case. Worth knowing it's possible though. I guess there is a problem elsewhere in my app then. Thanks. – Matt Lishman May 12 '16 at 13:54