[英]Communication between directives (and other parts) in AngularJS
I'm looking for guidelines about when and why should I use the "require" option in the directive definition, why not communicate just using the Scope - like most of the times in Angular ? 我正在寻找关于何时以及为什么要在指令定义中使用“require”选项的指南,为什么不使用Scope进行通信 - 就像Angular中的大多数时候一样? How is it, that suddenly in directives, I ask for the controller itself and not just attaching things to the scope(s) ? 怎么样,突然在指令中,我要求控制器本身,而不只是将东西附加到范围?
Generally speaking - there are many ways to communicate between directives/controllers/scopes in Angular - 一般来说 - Angular中的指令/控制器/作用域之间有很多通信方式 -
And while I understand how they work technically, it's not clear to me what are the guidelines to decide which one to use and why. 虽然我理解它们在技术上是如何工作的,但我不清楚决定使用哪一个以及为什么使用哪些指南。
Will be happy for some general/high level guidelines. 对于某些一般/高级指南感到高兴。 Thanks. 谢谢。
require
is particularly useful if you want to create custom form controls (see section Implementing custom from controls ) -- ie, you want to create your own form control with a directive. 如果要创建自定义表单控件, require
特别有用(请参阅从控件实现自定义部分) - 即,您希望使用指令创建自己的表单控件。 You can require
the ngModelController to get access a lot of existing functionality via its API/functions. 您可以require
ngModelController通过其API /函数访问许多现有功能。
Another use case is found on the AngularJS home page, section Create Components , where the pane
directive uses require: '^tabs'
to get access to the tabs
controller. 另一个用例可以在AngularJS主页的Create Components部分找到,其中pane
指令使用require: '^tabs'
来访问tabs
控制器。 Since both of these components/directives create isolate scopes, scope inheritance is not an option. 由于这两个组件/指令都创建了隔离范围,因此范围继承不是一种选择。 A service wouldn't be a good fit either, since your app could have multiple tabs
directives. 服务也不合适,因为您的应用程序可能有多个tabs
指令。 So, in this case, the controller is used as a means for the pane
directive to be able to affect the tabs
scope -- to be able to get at the scope. 因此,在这种情况下,控制器用作pane
指令的一种手段,以便能够影响tabs
范围 - 以便能够获得范围。 Without using require
, the pane
directive can't get at the tabs
scope. 不使用require
, pane
指令无法进入tabs
范围。 I discuss this in more detail (with a picture) in this SO answer: 'this' vs $scope in AngularJS controllers 我在这个SO答案中更详细地讨论了这个(带图片): AngularJS控制器中的'this'与$ scope
require
can only be used if the controller-of-interest is defined on the same element (eg, ngModelController
), or if there is a hierarchy (eg, pane -> tab). 如果感兴趣的控制器是在同一元素(例如, ngModelController
)上定义的,或者如果存在层次结构(例如,窗格 - >选项卡),则只能使用require
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.