Angular How to manage a service directive?
I am trying to make a Service that manages a directive.
Thus, the goal is to use the Service in the controller to ask the Directorate to do something.
eg. SomeService.tellSomething('ok');
calls directive with parameter
I know what we can use $rootScope.$broadcast
to send / fire an event, but I honestly don't know if this is good practice ...
Any tips / techniques?
source to share
You can use the pub / sub template for this. For example:
Add a method to your service subscribeToTellsomething
. Inject your service into the directive as a dependency and sign its directive when it is linked (reference method). Now make a service to publish all subscribers when the method is called tellSomething
.
source to share
You can also use the clock pattern for this, the pub / sub method is also viable, but it works more and I think $ broadcast actually uses the same pattern behind the scenes, but don't quote me on that.
When looking at the clock, there is something like this:
MyService.getSomething = function()
{
return something;
}
in your directive:
$scope.$watch(function() {
return MyService.getSomething();
}, function(newSomething) {
//do your thing
});
source to share