0
我在我的角度应用程序中有几个模板,我打算动态插入它们,其中一些可能需要共享数据,甚至可能使用相同的控制器。'Controller as'语法或服务?
我最近见过很多'ng-controller as'语法的例子,作为实现这一点的一种方式,并且我读过的大部分内容都支持这种方法,但我不知道,我感到可疑关于它。
我想知道什么是做这样的事情(每格是一个插入片段/模板)的优点和/或缺点:
<div ng-controller="mainController as main">
mainController: <input type="text" ng-model="main.someValue" />
main.someValue: {{ main.someValue }}
<div ng-controller="anotherController as another">
anotherController: <input type="text" ng-model="another.someValue" />
main.someValue: {{ main.someValue }}
</div>
</div>
当我可以做这样的事情:
<div ng-controller="mainController">
mainController: <input type="text" ng-model="someValue" />
someValue: {{ someValue }}
</div>
<div ng-controller="anotherController">
anotherController: <input type="text" ng-model="anotherValue" />
someValue: {{ someValue }}
</div>
有一个服务来连接我的两个模板中的数据。
谢谢!
但是,如果我必须通过控制器的命名空间来主持我的变量,那么避免点符号是不是毫无意义?例如,如果我要创建一个新的代码片段,我需要知道每个控制器的名称空间并相应地写入它,与服务选项相反,我将只使用控制器数据,并且服务将负责管理JS端的连接/绑定。为了共享数据的目的,必须嵌入片段并不是不自然,而不是因为它在DOM中有意义吗? – Jassel 2015-02-24 15:59:39