简体   繁体   中英

AngularJS - Child directive uses same data as parent. How to share?

I have a child directive that requires the same data as some of the parent pages that use it.

What is the best way to share data?

Should the child directive make the same API call as the parent?

Or should the parent send data to the directive via attributes?

I think that it depends.

If the parent and child directive are ever going to be re-used separately (meaning you could use one without the other) then you would DEFINITELY want to use attributes API to pass data into the child directive.

If they are always going to be used together, then you could do one of the following:

  • Use attributes to pass the value
  • Remove the isolate scope from the child and just have the child scope inherit the values from the parent scope. I hate it when people do this, but to each their own.
  • Have a service that caches the values, and they both call the service and get the same values back.
  • You could have the parent scope broadcast the data down to it's children using the scope eventing system.

All of these will work. You need to discuss with your team what they like the most and what you all think you should adopt as your regular pattern. After that, you just implement away.

Good luck!

I guess you described the right solution. It is better to pass data to directive trough attributes, and make directive only display that. But if you still want to make a call to api in the directive, then I would recommend to extract api call to service, and cache promise inside the service. This plugin can be useful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM