I'm struggling with organizing components within a complex AngularJS application that I've been maintaining, and I could really use some advice as I feel like I've hit a wall. Your patience is much appreciated!
Background:
I have several directives that need to interact with each other. Initially, I decided to define a controller in each directive to provide an API for other directives to utilize. While I am familiar with the require
property in directives and how it can be used to access parent directive controllers, my current situation doesn't quite align with this approach.
Instead of relying on require
, the existing codebase I'm working with tends to directly add directives to the DOM and then compile them afterwards. This was likely done to allow for more flexibility in customizing how directives interdepend.
Below is a snippet from the demonstration Plunker's link
function which I created to illustrate the issue I'm encountering. Notice how directives are added to the DOM and compiled subsequently. I attempted to simplify the actual code I'm dealing with since I cannot share it in its entirety.
link: function(scope, elem) {
scope.data = '...';
var d2Elem = elem.find('li').eq(0);
d2Elem.attr('d2', '');
var input = angular.element('<input type="text" ng-model="data">');
elem.find('li').eq(-1).append(input);
$compile(d2Elem)(scope);
$compile(input)(scope);
// Able to get d1 directive controller
console.log(elem.controller('d1'));
// Not able to get compiled d2 directive controller
console.log(d2Elem.controller('d2'));
// Able to get compiled ng-model directive controller
console.log(input.controller('ngModel'));
}
Inquiry:
Can someone please clarify why I am observing the behavior described in my Plunker? Why is it that after compiling a custom directive (i.e. d2
), I cannot access its corresponding controller even though it is defined in the directive?
In contrast, I noticed that I am able to retrieve the controller of the built-in ng-model
directive after compilation.
Another thought on my mind: Is the method I outlined the most efficient way to handle directives that need to communicate with one another if they do not necessarily have strict parent-child connections?
Your insights would be greatly valued!