在AngularJS指令(和其他地区)之间的通信 [英] Communication between directives (and other parts) in AngularJS
问题描述
我在寻找什么时候,为什么我应该使用需要选项,在指令中定义的准则,
最喜欢的角时代 - 为什么使用范围不只是沟通?
它是如何,这突然的指令,我要求控制器本身,而不仅仅是连接东西的范围(S)?
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 ? 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 -
- 范围继承。
- RootScope发出。
- 服务(出厂/服务/供应商)。
- 在指令要求的控制器。
- 需要新的示波器/分离范围/正常范围的指令。
- 更?
虽然我知道他们在技术上是如何工作的,这不是很清楚,我是什么来决定使用哪一个,为什么准则。
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.
推荐答案
要求
如果你想创建的自定义表单控件(见的实现从控制定制的) - 也就是说,你想创建一个自己的表单控件指示。您可以要求
ngModelController 获得通过其API /函数访问了很多现有的功能。
require
is particularly useful if you want to create custom form controls (see section Implementing custom from controls) -- i.e., you want to create your own form control with a directive. You can require
the ngModelController to get access a lot of existing functionality via its API/functions.
另一个用例是AngularJS主页上发现,部分的创建组件的,其中面板
指令使用要求:'^标签
来获得访问标签
控制器。因为这两个组件/指令创建分离的范围,范围的继承是不是一种选择。服务不会是一个不错的选择,因为相关您的应用程序可以有多个标签
指令。因此,在这种情况下,控制器被用作一种手段窗格
指令,以便能够影响标签
范围 - 能够获得在范围。如果不使用要求
的面板
指令不能在标签获得
范围。我在此更详细的(有图)讨论这个SO回答:<一href=\"http://stackoverflow.com/questions/11605917/this-vs-scope-in-angularjs-controllers/14168699#14168699\">this VS在AngularJS控制器$范围
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. 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. 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. Without using require
, the pane
directive can't get at the tabs
scope. I discuss this in more detail (with a picture) in this SO answer: this vs $scope in AngularJS controllers
要求
只能如果所使用的控制器的利益是相同的元素(例如, ngModelController
),或者如果有一个层级(例如,窗格 - >标签)
require
can only be used if the controller-of-interest is defined on the same element (e.g., ngModelController
), or if there is a hierarchy (e.g., pane -> tab).
这篇关于在AngularJS指令(和其他地区)之间的通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!