Reputation: 1582
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 -
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.
Upvotes: 3
Views: 851
Reputation: 364677
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.
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 (e.g., ngModelController
), or if there is a hierarchy (e.g., pane -> tab).
Upvotes: 2