I'm trying out AngularJS and I'm attempting to use TypeScript classes to get prepared for a large project. The problem I'm having is that the this
of the controller class is not being binded to the scope inside the portion of the DOM where the ng-controller
directive is.
Starting with the following TypeScript code:
angular.module('testApp')
.controller('TypeScriptController', () => new TypeScriptController())
// Controller implementation via TypeScript
class TypeScriptController {
text = "Please click the button";
constructor() {}
buttonClick () {
this.text = "The button was clicked";
}
}
And binding the controller to the DOM using
<main ng-controller="TypeScriptController as TSCtrl">
If I implement this using the standard ES5 function style it works fine (see first half of code snippet below). However the class version does not. Now I can pass in the $scope
variable to the controller and bind a property of $scope
to this
but then the controllerAs
syntax in the HTML is ignored. However, I'd like to avoid passing $scope
to every controller.
I know that AngularJS 1.3 introduced a bindToController
option for directives but I don't see how that could be applied in this context.
Example:
In this example showing the ES5 and TypeScript implementation of a controller. The controller simply contains a method that the ng-click
calls to write text below the button. The ES5 version works. The TypeScript version does not. I've also implemented this in a Plunker
angular.module('testApp', [])
.controller('MainController', MainController);
function MainController() {
this.text = "Please click the button";
this.buttonClick = function() {
this.text = "The button was clicked";
};
};
// Compiled from TypeScript source
angular.module('testApp').controller('TypeScriptController', function() {
return new TypeScriptController();
});
// Controller implementation via TypeScript
var TypeScriptController = (function() {
function TypeScriptController() {
this.text = "Please click the button";
}
TypeScriptController.prototype.buttonClick = function() {
this.text = "The button was clicked";
};
return TypeScriptController;
})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body ng-app="testApp">
<main ng-controller="MainController as mainCtrl">
<h1>Hello World!</h1>
<p>
<input type="button" name="testInput" value="Test button" ng-click="mainCtrl.buttonClick()">
</p>
<p>{{mainCtrl.text}}</p>
</main>
<main ng-controller="TypeScriptController as TSCtrl">
<h1>Hello TypeScript!</h1>
<p>
<input type="button" name="testInput" value="Test button" ng-click="TSCtrl.buttonClick()">
</p>
<p>{{TSCtrl.text}}</p>
</main>
</body>