I have a directive for parent scope, I also have another directive for child scope. In a template, I have several parent-child scope. Like this.
ParentScope1
- ChildScope1
ParentScope2
- ChildScope2
If I change a value in Parent, I will broadcast it to Child. I am using $rootScope.$broadcast
to broadcast from parent. I am using $rootScope.$on
to accept this change in child.
My problem is:
Now, If I change a value in ParentScope1, it will broadcast to ChildScope1. Then I will change a value in ParentScope2, it will broadcast to ChildScope2, but it will also broadcast to ChildScope1.
I want: Change a value in ParentScope1, it will broadcast to ChildScope1. Change a value in ParentScope2, it will broadcast to ChildScope2. I search online for some time but did not find the solution for it. Maybe I did not use the correct keywords for searching it. Please advise. Thank you.
You are looking for communication between parent and child directive, you can use below approach but both directive will be tightly coupled using this-
Require a controller - Get the handle of same node of parent node directive controller. Require: '^parnetDireName' is used to find the controller on parent node. Without ^, it will find for same node only. '?' is used when controller may not be available.''?^", "?^^", "^^". Fourth parameter of link function is used to get the controller. It can use the controller prop/method. You can also access multiple controller because Require will have array - require: ['^dir1','^dir2']. Link function will have cntrl array and it can be access through array element in the same sequence
Pre link and post link function for nested directive -
---------------------------------Another decoupled way --------------------- There are three ways to setup the relation between directive scope and containing controller scope- - Directive with shared scope with containing controller. Any new
item/modified item by directive will be part of parent scope. It is default or scope:false - Directive with inherited scope. Any new item added by directive will not be visible by containing controller. Directive scope can read all data from parent scope. Use scope:true property to activate it. Child can see parent data and can override or create new variable.
- Isolated scope. Both scope cannot read each other data. Object mapping is required to read the parent data. Directive scope mapping will have object name and same object will be passed from html. There are three ways to receive the parameter- - Complete object Data -> '=' is used - Simple value like flag as a String- '@' is used . '@sampleVar', where sampleVar is the name of variable in the html. Scope { cntrollerStrVarName: '@htmlStrVarName' }
- Function parameter - '&' is used to pass the parameter. Method parameter can be overridden using ({paramName: 'value'})