小编典典

Angular中“ Controller as”的优点是什么?

angularjs

在Angular中使用“ Controller as”语法有什么好处?只是为控制器创建别名还是在幕后有其他技术原因?

我是Angular的新手,想进一步了解这种语法。


阅读 335

收藏
2020-07-04

共1个答案

小编典典

controllerAs-syntax具有多个优点:

克拉蒂

考虑以下示例:

<div ng-controller="containerController">
    <h2>Improve your life!</h2>
    <p ng-controller="paragraphController">
        We talk about {{topic}} a lot, but do we really understand it? 
        Read this article to enhance your knowledge about {{topic}}
    </p>
</div>

仅通过阅读这段代码,您就无法分辨出哪里topic来的。它是否属于containerControllerparagraphController或仅仅是上面的sone输入的随机浮动范围变量?

通过使用controllerAs它很清楚:

<div ng-controller="containerController as container">
    <h2>Improve your life!</h2>
    <p ng-controller="paragraphController as paragraph">
        We talk about {{paragraph.topic}} a lot, but do we really understand it? 
        Read this article to enhance your knowledge about {{paragraph.topic}}
    </p>
</div>

您可以立即看到这topic是的属性paragraphController。这使代码在整体上更具可读性,因为它迫使开发人员明确谁属于函数和变量scope

绑定到属性

当您使用旧controller语法时,如果您在不同范围内对“ same”变量具有多个绑定,则可能会发生奇怪的事情。考虑以下示例:

<form ng-controller="myFormController">
    <input type="text" ng-model="somefield">

    <div ng-controller="someOtherController">
        <input type="text" ng-model="somefield">
    </div>
</form>

看起来两个input都绑定到同一个变量。他们不是。当您编辑第input一个时,一切看起来都正常,但是一旦编辑第二个,它们将不再同步。这与范围继承和绑定的工作方式有关。在绑定到对象属性(也就是当有这不会发生.在你的ng-model-attribute)。controllerAs无论如何,通过绑定到控制器对象的属性,它自然可以解决该问题:

<form ng-controller="myFormController as myForm">
    <input type="text" ng-model="myForm.somefield">

    <div ng-controller="someOtherController as other">
        <input type="text" ng-model="myForm.somefield">
    </div>
</form>

摆脱scope(大部分)

使用scope来创建controller旧的角度代码中的s的绑定很难读,很难理解,如果使用,则完全没有必要controllerAs。您不再需要注入scope每个元素controller,实际上,在大多数应用程序中您可能都不会注入它(如果要使用角度事件系统,则仍然需要这样做)。这样可以使控制器代码更简洁,样板更少。

为Angular 2做准备

在angular2中,scope将消失,我们将所有内容都编写为component。使用controllerAs让您无需工作就可以工作,scope并迫使您考虑面向组件的更多,从而为您(以及最终将要迁移的应用程序)为2.0更新做好准备。

2020-07-04