Logo Questions Linux Laravel Mysql Ubuntu Git Menu

Pass data from one directive to another

I have a directive that uses custom template, and I would like to pass the data from that directive to another one, and looking for the best possible way. So, I would like when the data inside the directive one changes, directive two get notified(watcher?), and acts upon it. So far, only the method with controller inside the directive one, and a watcher inside directive two for the controller method(from directive one) makes sense. Is there a a better way for this ?

--------------           --------------
| directive 1 |---data-->| directive 2 |
|             |          |             |
---------------          --------------
like image 210
Zed Avatar asked Mar 15 '23 22:03


2 Answers

You can use the $broadcast on the rootScope:

On the first directive:

$rootScope.$broadcast("NEW_EVENT", data);

On the other directive:

scope.$on("NEW_EVENT", function(event, data){
           //use the data

Take a look at this Understanding Angular’s $scope and $rootScope event system $emit, $broadcast and $on

like image 140
Atropo Avatar answered Mar 27 '23 09:03


You can use either $broadcast or services


if you want to use values of one directive into another then

 return {
        restrict: 'A',

        link: function (scope, el, attrs) {

second directive

 return {
        restrict: 'A',

        link: function (scope, el, attrs) {
like image 33
Shubham Nigam Avatar answered Mar 27 '23 09:03

Shubham Nigam