Angular中"Controller as"的优势是什么?

Par*_*ram 3 angularjs

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

我是Angular的新手,想要了解有关此语法的更多信息.

Lio*_*onC 14

controllerAs-syntax有多个优点:

Clartiy

请考虑以下示例:

<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>
Run Code Online (Sandbox Code Playgroud)

只是通过阅读这段代码,你无法分辨出topic来自哪里.它是属于containerController,paragraphController或者只是来自上面输入的随机浮动范围变量?

通过使用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>
Run Code Online (Sandbox Code Playgroud)

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

绑定到属性

当您使用旧controller语法时,如果在"相同"变量的不同范围内有多个绑定,则会发生奇怪的事情.考虑这个例子:

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

    <div ng-controller="someOtherController">
        <input type="text" ng-model="somefield">
    </div>
</form>
Run Code Online (Sandbox Code Playgroud)

看起来两个inputs都绑定到同一个变量.他们不是.当你编辑第input一个时,一切看起来都可以正常工作,但是一旦你编辑第二个,它们将不再同步.这与范围继承和绑定工作的方式有关(并且在SO上有一个很好的答案).绑定到对象属性时(即,.在您的ng-model-attribute中存在a )时,不会发生这种情况.与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>
Run Code Online (Sandbox Code Playgroud)

摆脱scope(大多数)

使用在旧角度代码中scope创建与controllers的绑定很难阅读,难以理解,如果使用则完全没有必要controllerAs.你不再需要注入scope每一个controller,事实上你可能不会在大多数应用程序中注入它(如果你想使用角度事件系统,你仍然需要这样做).这导致更清晰的控制器代码具有更少的奇怪样板.

它为Angular 2做准备

在角度2中,scope将会消失,我们将把所有内容都写成组件.使用controllerAs可让您无需工作,scope并迫使您更多地考虑面向组件,从而为您(以及最终将要迁移的应用程序)做好准备以进行2.0更新.