This post is based on a StackOverflow answer by Oliver Wienand that I came across while researching the AngularJS pattern described below.
Data binding between controller and directive in AngularJS can be a tricky subject for the uninitiated (and often, even for the initiated). AngularJS is great at providing the magic that makes data flow easily between components on the front end – except when it’s not. This post is an examination of one of the cases where not everything is straightforward.
Passing a callback function into a directive with isolate scope is simple – just a matter of creating the binding in the scope definition (callback: ‘&’). However, there is no built-in equivalent for exposing a directive function to the parent directive or controller. That is, if we have the (truncated) directive definition below, we’re going to have to do some work before calling “foo” from the parent directive or controller.
Option 1: Events
Typically, communication between controllers and directives that do not share scope is handled with events. A $rootscope.$broadcast() from the parent with a corresponding scope.$on() listener in our directive would certainly get the job done and is a viable option (especially in the case where we need to carry out other, related operations in other directives at the same time). However, event firing/catching has a lot of performance overhead and isn’t the best option when we need to make an isolated call to a function defined in a child directive.
Option 2: Directive control objects
The alternative to firing and listening for events is to bind a control object in your directive. The control object is defined as a typical 2-way binding and passed in from the parent as usual. The first step is to define the control object in the parent (a controller, in this example):
Then, we pass it to the directive:
To which we have added a 2-way binding for the control object:
And finally, we can call foo() from the controller:
AngularJS puts a huge amount at our disposal as developers, and it can sometimes be daunting to pick the right tool for the job. I hope that this post has added to your toolbox and helped organize it (and your code) a bit better as well.