This is more of an organizational approach to solving this issue rather than a direct solution. My question itself is that if I have two directives which are not dependent on each other and can both work independently to serve their purposes. But if one of the directives is present then the other one needs to execute once the other is ready. In this case then what would be the logical way to make sure that it works out that way without the need to hardcode any function calls or events?
Lets say for example you have one directive which builds a grid of some sort:
angular.module('App').directive('appGrid',function() {
return function($scope, element) {
$scope.rows = ...
};
});
Then I have another directive that makes the element horizontally scrollable:
angular.module('App').directive('appPane',function() {
return function($scope, element) {
element.attachHorizontalScroll();
};
});
So an example of my HTML would look like this:
<div data-app-grid data-app-pane>
<div data-ng-repeat="row in rows">
<div data-ng-repeat="cell in row.cells">
{{ cell.data }}
</div>
</div>
</div>
Basically the appPane
directive needs to run after the appGrid
directive has been executed and the table is ready.
One solution I can think of is to watch the data to see when it is ready using the $scope.$watch
method, but this poses a problem since the change can occur multiple times and this would be bad design to redundantly update the page and it also poses a problem if multiple directives are writing to the same scope variable that is being watched.
Another solution is to have the first directive emit an event (something like elementReady) and then have the 2nd directive take over. But what about if the first directive isn't there? Then how would the 2nd directive know when to do it's job? There could be another directive which is basically an empty directive which just fires the event for all other elements, but this is a bit of hack. Also what happens if multiple other directives fire the elementReady
event?
One more solution is to create a 3rd directive which shares the logic between the two directives via a shared service. But this makes the 3rd directive fully reliant on both other directives as well as the shared services in between. This also require more, unnecessary testing code as well as actual code to write the directive (much more code compared to the 2nd solution, which would require only one + one lines of code).
Any ideas?