1

I have some nested directives as follows:

    <div ng-controller="MyCtrl">
       <parent sku="12345">
          <child>
          </child>
       </parent>
    </div>

Both the parent and child directives have an isolated scope but I need to share the SKU attribute value between the parent and the child so that the child has access to this value. This value will always be hardcoded in the HTML.

Ideally, I would like each of the directives to have their own individual controller as well as a parent controller that sits over the top of both (MyCtrl) and I was intending on giving each directive their own isolated scope and then picking and choosing which scope values I want to share between them. The problem is I dont know how to do this.

Plunkr can be found here...

https://plnkr.co/edit/2M4OMNdXHlzq2MG9ugo0?p=preview

6
  • 1
    Do you want to have HTML structure like you posted? Then you will need to deal with transcusion and render child somewhere inside parent template. Commented Jun 18, 2016 at 11:00
  • I currently have the HTML like that and have separate template file for the child and parent directives Commented Jun 18, 2016 at 11:19
  • This doesn't answer my question regarding sharing the scope values though Commented Jun 18, 2016 at 11:34
  • It actually answers :). But I can repeat it: with this structure you need to manually transclude parent content, then you can control scope. Commented Jun 18, 2016 at 12:00
  • 1
    I like what Aleksey suggests, check it out. With transclusion it could look like this: plnkr.co/edit/KlE4Ssl33arojhjeZRI9?p=preview Commented Jun 18, 2016 at 13:25

1 Answer 1

2

You can add getSku method to parent controller and then get this value in link function of child. Here's demo.
If you're using angular 1.5.* can also checkout components syntax. You'll be able to get similar results without link function.

Sign up to request clarification or add additional context in comments.

14 Comments

I like this answer as it allows you to keep the scopes isolated and have more control over what is passed in. I think this is also what the angular documentation suggests having looked at it. Using the transclusion option seems a bit convoluted for the requirements
Could you give me an example of the same thing with the components syntax please Aleksey?
Sure, here's example with the components
Thanks Aleksey. Perfect examples!
Expanding on this a bit...let's say in the parent controller you use a service to retrieve product data based on the sku used in the attribute. Is there any way we can use a callback that when this has finished the child directive retrieves this data
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.