I switched to using ES6 (Babel) in my new Angular project. ES6 classes cannot have variables. How do I set my $scope variable now??
Say I have a simple controller:
class MainController {
constructor ($timeout, events) {
'ngInject';
this.textMaker = "Hello!" //Option #1
} // constructor
textMaker(){ //Option #2
return "Hello!";
}
}
export default MainController;
My html looks like (controller is aut0matically injected during build, say):
<h1> {{textMaker}}</h1>
Both Option #1 and Option#2 don't seem to work. I get a blank heading. Such a simple thing.. what am i doing wrong?
When you assign a value to a property of the controller, you have to use the controllerAs syntax for the controller.
controllerAs in router or directive:
controllerAs: 'mainCtrl' // in router or in directive, you still need to state the controller property
controllerAs in ngController:
<div ng-controller="MainController as mainCtrl">
Get the property in the HTML:
<h1> {{mainCtrl.textMaker}}</h1>
If you want to use $scope, inject it normally, and don't use controllerAs:
constructor ($scope, $timeout, events) {
this.$scope = $scope; // assign $scope to a property of the controller, so it will be available in methods
this.$scope.prop = 'value'; // refer to properties on the scope in the constructor or methods
}
Html:
<h1> {{textMaker}}</h1>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With