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.

1 Answer 1

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.

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

1 Comment

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.

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.