Pass data from one directive to another

2019-06-27 09:19发布

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 |
|             |          |             |
---------------          --------------

2条回答
做个烂人
2楼-- · 2019-06-27 09:43

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

查看更多
再贱就再见
3楼-- · 2019-06-27 09:43

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);
}
}
});
查看更多
登录 后发表回答