2017-02-10 103 views
1

因此,在Angular 2中沒有控制器的語法,組件的屬性可以直接在模板中使用,例如,就像這個組件:如果Angular2沒有控制器A,爲什麼建議使用Angular 1.5+?

@Component({ 
    selector: 'component-a', 
    template: `<div class="component-a"> 
       <div class="counter" (click)="increment()">Component A: {{counter}}</div> 
       </div>` 
}) 
export class ComponentA { 

    counter = 0; 

    increment() { 
     this.counter += 1; 
    } 

} 

(從What is the analog of the 'controllerAs' directive's property in Angular 2 component?複製)

這就像我開始從一開始寫作角度的1.x < 1.5。然後「他們」說「最好使用controllerAs語法」。現在我的代碼中幾乎處處都有$ctrl.myThing。甚至更多的是,在一些教程中,他們建議你切換到控制器A以便更接近Angular 2.但是它似乎至少距離語法更遠?

我的意思是,我得到它,它是更好,當你使用的實際控制人的意見和做的東西,如:

<div ng-controller="MainCtrl"> 
    {{ title }} 
    <div ng-controller="AnotherCtrl"> 
    {{ title }} 
    <div ng-controller="YetAnotherCtrl"> 
     {{ title }} 
    </div> 
    </div> 
</div> 

但我從來沒有這樣做,反正和使用的指令/組件所有的這些情況。所以當我在Angular 1.5+中的整個體系結構基於組件時,那麼控制器的優勢是什麼?無論如何,我有一個孤立的範圍......那麼爲什麼不直接使用沒有控制器的答案,所以它的語法與Angular 2相同?我的意思是很容易遷移它,因爲我可以在項目中找到並替換所有$ctrl.,我只想了解在這種情況下哪些好處(如果有的話)。

爲了讓另一個例子: 這是

<button class="btn btn-default" ng-click="$ctrl.sayHello()"> 
    Hello {{$ctrl.somebinding}} 
    </button> 

者優先這個

<button class="btn btn-default" ng-click="sayHello()"> 
    Hello {{somebinding}} 
    </button> 

爲模板的角度1.5+ 組件隔離範圍如果是這樣爲什麼因爲後者的語法實際上更接近角2?

+0

你見過有沒有人在1.5中提出了控制器組件架構?我們經常使用controllerAs,直到我們開始使用組件思維進行開發,並且我們從未使用過controllerAs。 – isherwood

+0

快速撥號上我保留[此博客文章](https://teropa.info/blog/2015/10/18/refactoring-angular-apps-to-components.html),但我們不使用'controllerAs' ,而是對每個範圍使用默認的'$ ctrl'(技術上*是'controllerAs'的實現)。 – isherwood

+0

是的,爲什麼Angular 2中不需要'$ ctrl.'模板中的任何地方?就像你說的那樣,它在技術上就是controllerAs。 – bersling

回答

0

controllerAs應該用於指令和控制器,當然不是組件。 (一些庫如角引導,角材料,UI路由器沒有遷移到1.5-1.6,仍然需要控制器)

猜測大多數推薦'controllerAs'是在Angular 1.5之前編寫的 - 當沒有組件時。

我只是說在組件中,你有控制器作爲$ ctrl,並且在controllerAs語法中沒有必要。如果你感興趣,爲什麼默認情況下{{prop}}沒有對控制器屬性進行評估 - 核心角度服務$ parse在1.4中使用範圍 - 所以當他們添加組件時,他們顯然不能改變它。否則,以前的角度版本的所有書面代碼都會停止工作。

+0

但是它甚至對組件使用'$ ctrl'進行角度默認設置,請參閱https://docs.angularjs.org/guide/component。你怎麼說它不應該被用於組件? – bersling

+0

mb現在更清楚了,mb不是( –

相關問題