2

我在新的Angular项目中转而使用ES6(Babel)。 ES6类不能有变量。现在如何设置我的$ scope变量?如何访问ES6风格的Angular Controller中的范围变量?

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

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

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


    } // constructor 

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


} 


export default MainController; 

我的HTML看起来像(控制器构建过程中aut0matically注入,说):

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

两个选项#1和方案2不要” t似乎工作。我得到一个空白标题。这么简单的事情..我做错了什么?

+0

'如果你定义了'controllerAs'或'as'为控制器this'只会工作,在otherhand你能尝试注入'$ scope'做像这样的'this。$ scope.whatever'(我不确定这个) –

+0

我在我的ui路由器文件中定义了一个'controllerAs'。它的价值应该是什么?它是如何影响这一点的? –

+0

似乎有一个误解。您使用ES6的事实不会改变任何事情。您可以像使用ES5一样使用'$ scope'。 ES6“类”只是语法上的糖(还),而不是一个新的特征。 – zeroflagL

回答

6

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

  1. controllerAs在路由器或指令:

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

  2. controllerAs在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> 
+0

我的问题是没有说明模板中的控制器。谢谢。 –

0

让ellobrate一点就回答以上,为您拥有的ES6控制器类,您可以创建可以通过绑定更改值的函数。

例子:

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

然后你只需简单地点击事件调用whatIsTheName(),这是删除所有代码的$范围的好方法,这也使得转换到角2更好如果你仍然对角1

干杯