【问题标题】:What is the advantage of "Controller as" in Angular?Angular 中“Controller as”的优势是什么?
【发布时间】:2015-09-24 07:42:22
【问题描述】:

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

我是 Angular 的新手,想了解更多关于这种语法的信息。

【问题讨论】:

  • 最重要的是它可以更好地为您准备 Angular2

标签: angularjs


【解决方案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 来自哪里。它属于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>

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

绑定到属性

当您使用旧的controller 语法时,当您在不同范围内对“相同”变量进行多个绑定时,可能会发生奇怪的事情。考虑这个例子:

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

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

看起来inputs 都绑定到同一个变量。他们不是。当您首先编辑第一个 input 时,一切看起来都可以正常工作,但是一旦您编辑第二个,它们就不会再同步了。这与作用域继承和绑定的工作方式有关 (and there is an excellent answer on this on SO)。当您绑定到对象属性时(也就是当您的 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(大部分)

如果您使用controllerAs,使用scope 在旧的角度代码中创建到controllers 的绑定很难阅读、难以理解并且完全没有必要。您不再需要将scope 注入到每个controller 中,实际上您可能不会在大多数应用程序中注入它(如果您想使用角度事件系统,您仍然需要这样做)。这会产生更简洁的控制器代码和更少奇怪的样板。

它为 Angular 2 做准备

In angular 2, scope will be gone and we will write everything as components。使用controllerAs 可以让您在没有scope 的情况下工作,并迫使您更多地考虑面向组件,从而为您(以及您最终要迁移的应用程序)为2.0 更新做好准备。

【讨论】:

  • @LionC - 我不得不说这是一个非常清晰简洁的解释。在一次求职面试中,有人问我为什么从使用“$scope”转向“this”语法,我立即提到了“Controller As”语法。这家伙似乎对我的回答很满意。
  • @LionC 感谢您指出使用 $scope 如果您必须添加事件侦听器而不是 $scope 很有用。感谢您的差异。
猜你喜欢
  • 2014-08-03
  • 2015-03-05
  • 1970-01-01
  • 1970-01-01
  • 2011-02-12
  • 1970-01-01
  • 2012-02-10
  • 2015-01-16
  • 2011-03-25
相关资源
最近更新 更多