栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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
或仅仅是上面的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更新做好准备。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/448290.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号