2

我在我的新 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;

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

<h1> {{textMaker}}</h1>

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

4

2 回答 2

9

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

  1. 控制器在路由器或指令中:

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

  2. 控制器如 ngController 中的:

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

获取 HTML 中的属性:

<h1> {{mainCtrl.textMaker}}</h1>

如果要使用$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

}

html:

<h1> {{textMaker}}</h1>
于 2015-09-27T14:04:01.017 回答
0

让我们稍微解释一下上面的答案,对于您拥有的 ES6 控制器类,您可以创建可以通过绑定更改值的函数。

例子:

class something{
 constructor(){
  this._Name = '';
 }
whatIsTheName(){
 this._Name = 'Unix Rox!'
}
export default something;
}

然后您只需在单击事件上调用 whatIsTheName(),这是从所有代码中删除 $scope 的好方法,如果您仍在 Angular 1 上,它还可以使您更好地转换到 Angular 2。

干杯

于 2016-07-05T14:37:21.727 回答