Ali Salehi
Ali Salehi

Reputation: 6999

Sharing data across directives design pattern in Angular

I am trying to design the interaction between four directives.

Directive 1: Creates an HTML form with field for student_id.

Directive 2: When student_id is set/changed in directive1, this directive downloads student(s) information from the database. The purpose of directive2 is to make sure data is downloaded once and used by other directives.

Directive 3: When a student_data is downloaded by directive2, this directive creates a table of the student's performance.

Directive 4: When a student_data is downloaded by directive2, this directive creates a chart of the student's performance.

Directive2/3/4 are pretty generic and I will need them in multiple pages.

Directive 2 sends a request to server so data won't be available for directive3/4 immediately. The data in the form generated by directive 1 may be modified, in this case, all linked directives need to be reevaluated.

What is proper design for this scenario? Should they all be nested like below?

 <d1><d2><d3></d3><d4></d4></d2></d1>  (scope:require ...)

Should I use a service with $broadcast/$on or modify the $rootScope. or something else?

Upvotes: 0

Views: 56

Answers (1)

atinder
atinder

Reputation: 2090

I think using service should be the cleaner way to do it. Polluting rootScope unnecessarily should be avoided. Create a basic service with setters and getters and inject in each directive of yours. Since service is singleton, you will have the same data available across all the directives.

Upvotes: 3

Related Questions