There is a directive implemented on my webpage with an assigned id attribute, regardless of its functionality. Now, I need a second directive that essentially triggers the first one.
Here is an example of what I aim to achieve:
<body>
<!-- various elements -->
<my-directive id="test"></my-directive>
<!-- various elements -->
<controlling-directive directive-id="test"></controlling-directive>
</body>
The controllingDirective
could be defined as follows:
.directive('controllingDirective', function() {
link: function(scope, elem, attrs) {
element.on('click', function(){
// Call directive with attrs.directiveId
});
}
}
The question arises: How can this be achieved and what is the optimal approach?
I have considered two methods:
One involves using document.getElementById and angular.element(..).isolateScope() as shown below:
.directive('myDirective', function() {
scope: {},
link: function(scope, elem, attrs) {
scope.actionToStart = function() {...};
}
}
.directive('controllingDirective', function() {
link: function(scope, elem, attrs) {
element.on('click', function(){
angular.element(document.getElementById(attrs.directiveId))
.isolateScope().actionToStart();
});
}
}
Alternatively, an event on $rootScope could be utilized:
.directive('myDirective', function($rootScope) {
scope: {},
link: function(scope, elem, attrs) {
$rootScope.$on(attrs.id + 'Start', function(){...});
}
}
.directive('controllingDirective', function($rootScope) {
link: function(scope, elem, attrs) {
element.on('click', function(){
$rootScope.$emit(attrs.directiveId + 'Start');
});
}
}
Neither of these options feels ideal. Is there a simpler solution that I may be overlooking for achieving this task?
It's important to note that the 'require' option cannot be used since the directives are not interconnected in the DOM structure.