简体   繁体   中英

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 ? 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 -

  • Scope inheritance.
  • RootScope "emits".
  • Services (factory/service/provider).
  • Requiring controllers in directives.
  • Requiring new Scope/ isolate scope / "normal" scope in directives.
  • More?

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. You can require the ngModelController to get access a lot of existing functionality via its API/functions.

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

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM