Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access scope variable in ES6 styled Angular Controller?

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?

like image 792
Shubham Kanodia Avatar asked Feb 04 '26 12:02

Shubham Kanodia


1 Answers

When you assign a value to a property of the controller, you have to use the controllerAs syntax for the controller.

  1. controllerAs in router or directive:

    controllerAs: 'mainCtrl' // in router or in directive, you still need to state the controller property

  2. 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>
like image 139
Ori Drori Avatar answered Feb 07 '26 02:02

Ori Drori



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!