因此,在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