Access value of a variable of child directive in parent directive

507 Views Asked by At

How to access a variable of child directive in parent directive? I have a parent directive like:

<parent-directive>
  <child-directive></child-directive>
</parent-directive>

child directive contains an object "states.visible" I want to access that in parent directive.

1

There are 1 best solutions below

8
Phil Ninan On BEST ANSWER

I think the AngularJs way of doing this would be accomplished with implementing an output in the child directive. Every time the "states" object changes the child calls the output function and the parent can do whatever it wants with it.

AngularJS v1.5+ Method:

HTML

<parent-directive>
  <child-directive on-state-change="$ctrl.stateChange($stateChangeObj)"></child-directive>
</parent-directive>

Child Controller

    $scope.$watch('$ctrl.state', function(n, old){
        ctrl.onStateChange({$stateChangeObj: n});
    })

Parent Controller

ctrl.stateChange = function(state){
    // do something
}

https://docs.angularjs.org/guide/component#component-based-application-architecture

Note: Component based architecture was introduced in AngularJS v1.5.


Prior to AngularJS v1.5 Method:

this should technically work the same with a two way bound function. except the html would look like this

on-state-change="$ctrl.stateChange"

instead of

on-state-change="$ctrl.stateChange($stateChangeObj)"

. then in the child it would be

ctrl.onStateChange(n);

instead of

 ctrl.onStateChange({stateChangeObj: n});