2

what is the best way to have two directives talk to each other? Lets say I have the following setup:

<drop-uploader></drop-uploader>
<drop-uploader></drop-uploader>

<progress-bar></progress-bar>

whats the best way to have the "uploader" directive notify the "progress bar" directive? Is the best way to use events on the rootScope or use a service? Is there a way to reference a directive as an attribute on another directive to access its scope? Something like this...

<drop-uploader progress-bar="thisone"></drop-uploader>
<drop-uploader progress-bar="thisone"></drop-uploader>

<progress-bar name="thisone"></progress-bar>
nrivero
  • 281
  • 1
  • 9
  • 1
    This might help [Egghead.io - AngularJS - Directive to Directive Communication](http://youtu.be/rzMrBIVuxgM) – jnthnjns Sep 20 '13 at 14:33
  • 1
    I saw that video but he is demonstrating how to communicate between two directives on the same dom element. Great video though. – nrivero Sep 20 '13 at 14:42

2 Answers2

1

There are options for sharing data between controllers (check for "require" in the docs) but as far as I have understood it you can't use that method to share data between siblings. It has to be parent/child (someone correct me if I am wrong).

You can however share data using services. There is only one instance of each service no matter how many different controllers/services/directives invoke it, so setting the data in one will update the other.

The sollution outlined here will work for directives as well as controllers: Angularjs, passing scope between routes

Community
  • 1
  • 1
Erik Honn
  • 7,576
  • 5
  • 33
  • 42
  • Btw, if you are just signaling, not actually sharing data two ways, I think a broadcast might better like Chandermani mentioned. – Erik Honn Sep 20 '13 at 14:48
  • so I figured out a way to do my proposed setup using angular.element to select the element and calling scope() on that element to get its scope. just not sure of the pros/cons of doing it that way. – nrivero Sep 20 '13 at 14:59
1

I would go for events using $rootScope $broadcast as all other mechanism introduce a state into the system which you need to keep in sync.

Be it using a property on the rootscope or creating a service which has a shared variable.

Also if the scenario fits into a eventing pattern then $broadcast would be better.

Chandermani
  • 42,589
  • 12
  • 85
  • 88