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 |
| | | |
--------------- --------------
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
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);
}
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With