如何在ES6样式的角度控制器中访问范围变量?

Shu*_*dia 2 javascript ecmascript-harmony angularjs ecmascript-6 angular-controller

我在我的新Angular项目中转而使用ES6(Babel).ES6类不能有变量.我如何设置我的$ scope变量?

说我有一个简单的控制器:

class MainController {
    constructor ($timeout, events) {
        'ngInject';

            this.textMaker = "Hello!" //Option #1


    } // constructor

    textMaker(){            //Option #2
        return "Hello!";
    }


} 


export default MainController;
Run Code Online (Sandbox Code Playgroud)

我的html看起来像(在构建过程中控制器是自动注入的,比方说):

<h1> {{textMaker}}</h1>
Run Code Online (Sandbox Code Playgroud)

选项#1和选项#2似乎都不起作用.我得到一个空白的标题.这么简单的事情......我做错了什么?

Ori*_*ori 9

为控制器的属性赋值时,必须使用控制器的controllerAs语法.

  1. routerAs在路由器或指令中:

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

  2. ngController中的controllerAs:

    <div ng-controller="MainController as mainCtrl">

获取HTML中的属性:

<h1> {{mainCtrl.textMaker}}</h1>
Run Code Online (Sandbox Code Playgroud)

如果你想使用$scope,请正常注入,不要使用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

}
Run Code Online (Sandbox Code Playgroud)

HTML:

<h1> {{textMaker}}</h1>
Run Code Online (Sandbox Code Playgroud)