When using directives, I sometimes find the need to pass data through nested directives, even though the intermediate directives don't use the data, they need to pass it down to their child directives. This is annoying because it couples directives and makes the wiring quite hard.
Consider this example: The MainCtrl holds some data in an array and uses a 'first-directive'. This directive then uses 'second-directive' which needs access to the data from MainCtrl. Therefore, 'first-directive' needs to get the data from MainCtrl and pass it through - and itself it does nothing with the data:
<body ng-controller="MainCtrl as mainCtrl">
<first-directive data="mainCtrl.items"></first-directive>
</body>
and the javascript:
app.controller('MainCtrl', function($scope) {
var self = this;
self.items = ["first", "second"];
});
app.directive('firstDirective', function() {
return {
scope: {
data: '='
},
template: '<second-directive data="data"></second-directive>'
};
});
app.directive('secondDirective', function() {
return {
scope: {
data: '='
},
template: 'second directive data: {{data}}'
};
});
How could the above code be changed such that 'first-directive' does not need to know about data? Is this a common problem in angular? How is this usually solved? The problem gets even worse when there is more nesting of directives involved.
Plunker: https://plnkr.co/edit/aKWBq5DLOLFvamk6gx4e?p=preview
Edit: I've found a blog post discussing this. It recommend the use of 'require' on the nested directives. What do you think? http://www.codelord.net/2014/03/30/writing-more-maintainable-angular-dot-js-directives/