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.