因此,在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?
你見過有沒有人在1.5中提出了控制器組件架構?我們經常使用controllerAs,直到我們開始使用組件思維進行開發,並且我們從未使用過controllerAs。 – isherwood
快速撥號上我保留[此博客文章](https://teropa.info/blog/2015/10/18/refactoring-angular-apps-to-components.html),但我們不使用'controllerAs' ,而是對每個範圍使用默認的'$ ctrl'(技術上*是'controllerAs'的實現)。 – isherwood
是的,爲什麼Angular 2中不需要'$ ctrl.'模板中的任何地方?就像你說的那樣,它在技術上就是controllerAs。 – bersling