flow3r flow3r - 22 days ago 7
Javascript Question

Communication between custom sibling directives

I have the following code:

<tr ng-repeat="row in ctrl.tableData">
<td><status></status></td>
<td>{{row.id}}</td>
<td>{{row.firstName}}</td>
<td>{{row.lastName}}</td>
<td><number-picker></number-picker></td>
</tr>


Where 'status 'and 'number-picker' are my custome directives.


I want to change the visibility of 'status' depending on some status of 'number-picker' in the same row. As they are in a grid, there are multiple instances of both directives.


My best solutions so far:

1. 'ng-repeat' creates a new scope for every 'tr' so I can share a variable between 'status' and 'number-picker' - this method assumes that I have a row variable in $scope, which is bad

2. $broadcast an event from 'number-picker' and catch it with $on on 'status' still using the shared $scope


Is there any cleaner way of achieving this behaviour?
Thanks in advance!

---EDIT---

Thanks, Vanojx1!
Your suggestion led me to a solution which I really like.

I have made some modifications to your code so now it is very similar to what I wanted to do.


The point is that now I can use 'numIsEven' to indicate the change of some inner state of number-picker to any other sibling directives.




PLUNKER

Answer

Add an attribute like shared-info:

<tr ng-repeat="row in ctrl.tableData">
  <td><status shared-info="row.sharedInfo"></status></td>
  <td>{{row.id}}</td>                    
  <td>{{row.firstName}}</td>
  <td>{{row.lastName}}</td>                 
  <td><number-picker shared-info="row.sharedInfo"></number-picker></td>
</tr>

then define directives scope using '=' DOC:

.....
    scope: {
        sharedInfo: '='
    },
....

row.sharedInfo will be shared between directives

Plunker

Comments