nrivero
nrivero

Reputation: 281

communicating between two separate Directives

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>

Upvotes: 2

Views: 1312

Answers (2)

Chandermani
Chandermani

Reputation: 42669

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.

Upvotes: 1

Erik Honn
Erik Honn

Reputation: 7576

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

Upvotes: 1

Related Questions