Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS parent directive communicate with child directive

Consider two nested directives with isolate scopes:

<dctv1>
    <dctv2></dctv2>
<dctv1>

If I want dctv2 to talk to dctv1 I have may options:

  1. I may require the controller of dctv1 in the definition of dctv2 using the require:'^dctv1'
  2. I may call an expression on the parent scope with the wrapper <dctv2 callParent="hello()"></dctv2> and scope:{callParent:'&'}
  3. I can also use $scope.$emit in dctv2 but then all parent scopes will hear the message.

Now I want dctv1 to talk to dctv2.

  1. The only way I may accomplish this is to use $scope.$broadcast, but then all children will hear.

By talk to here i mean call a function or similar. Don't want to set up watches clogging the digestloop.

How can I make dctv1 notify dctv2 in the best way, making them loose-coupled? I should just be able to remove dctv2 without errors.

like image 767
user1506145 Avatar asked Feb 12 '15 13:02

user1506145


1 Answers

Take a look at AngularJS NgModelController for some ideas.

Each <dctv2> directive would require <dvtv1> to have it's controller injected. You can then add objects or callbacks to properties of that controller, and remove them when <dctv2> is destroyed.

<dvtv1> would not talk directly to children, but would trigger callbacks bound to it's properties.

For example;

NgModelController has $parsers and $formatters that are an array of function callbacks. You push your own functions into the array to extend that controllers behavior.

When NgModelController performs input validation it's basically talking to other directives via these properties.

like image 106
Reactgular Avatar answered Oct 13 '22 05:10

Reactgular