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

乾杯