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

Zed


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

Atropo


You can use either $broadcast or services

$rootScope.$broadcast("anotherDirective");

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

angular.module('app',[]).directive('directOne',function(serviceOne){
 return {
        restrict: 'A',

        link: function (scope, el, attrs) {
serviceOne.variable1=anyValue;
}
}
});

second directive

angular.module('app',[]).directive('directSec',function(serviceOne){
 return {
        restrict: 'A',

        link: function (scope, el, attrs) {
console.log(serviceOne.variable1);
}
}
});
like image 33
Shubham Nigam Avatar answered Mar 27 '23 09:03

Shubham Nigam