How to communicate between directives in AngularJS



Image not found!!

In AngularJS, directives are a powerful feature that allows you to extend HTML with new behavior and create reusable components. When you have multiple directives in your application and need them to communicate with each other, you can use various methods. Here are some common approaches:

  1. Using a Shared Service:

    • Create a service that will act as a mediator between the directives.
    • Inject the service into both directives.
    • Use the service to share data or trigger actions between the directives.
    javascript
    // Shared Service angular.module('yourModule').service('sharedService', function() { var sharedData = {}; return { getData: function() { return sharedData; }, setData: function(data) { sharedData = data; } }; }); // Directive 1 angular.module('yourModule').directive('directiveOne', ['sharedService', function(sharedService) { return { link: function(scope, element, attrs) { // Use sharedService to get or set data var data = sharedService.getData(); // Do something with the data } }; }]); // Directive 2 angular.module('yourModule').directive('directiveTwo', ['sharedService', function(sharedService) { return { link: function(scope, element, attrs) { // Use sharedService to get or set data var data = sharedService.getData(); // Do something with the data } }; }]);
  2. Using $rootScope:

    • You can use $rootScope to broadcast events between directives.
    javascript
    // Directive 1 angular.module('yourModule').directive('directiveOne', ['$rootScope', function($rootScope) { return { link: function(scope, element, attrs) { // Broadcast an event $rootScope.$broadcast('someEvent', { data: 'someData' }); } }; }]); // Directive 2 angular.module('yourModule').directive('directiveTwo', ['$rootScope', function($rootScope) { return { link: function(scope, element, attrs) { // Listen for the event var unbind = $rootScope.$on('someEvent', function(event, args) { // Do something with the data console.log(args.data); }); // Make sure to unbind the event when the directive is destroyed scope.$on('$destroy', unbind); } }; }]);

Choose the method that best fits your application's architecture and requirements. Using a shared service is generally preferred for more complex scenarios, as it provides a cleaner and more maintainable solution.