0

I'm trying to figure out how to make a child directive communicate with it's parent directive

I basically have this html markup

<myPanel>
    <myData dataId={{dataId}}></myData>
</myPanel>

In the myData directive, if there is no data available, I want to hide the myPanel.

In the myData directive controller I've tried

$scope.$emit('HideParent');

And in the myPanel controller I've tried

$scope.$on('HideParent', function () { $scope.hide = true; });

And also

$scope.$watch('HideParent', function () { if (value) { $scope.hide = true; }});

In either situation, the myPanel directive isn't receiving the $emit

mrb398
  • 1,277
  • 4
  • 24
  • 32
  • 1
    rather than using $emit/$on. use controller on parent directive – harishr Apr 16 '15 at 16:01
  • Read the section about [communication between directives](https://docs.angularjs.org/guide/directive#creating-directives-that-communicate) in the directive guide – New Dev Apr 16 '15 at 16:07
  • you could try $rootscope.$broadcast('HideParent'); – Delta Apr 16 '15 at 16:07
  • possible duplicate of [How to share scope between two directive in AngularJs](http://stackoverflow.com/questions/18465851/how-to-share-scope-between-two-directive-in-angularjs) – tpie Apr 16 '15 at 16:29

2 Answers2

1

You may create controller in myPanel directive. Then require this controller in myData directive. And when child directive has no data, call controller method to hide parent.

For example in you parent (myPanel) directive:

controller: function($scope, $element){
  $scope.show = true;

  this.hidePanel = function(){
    $scope.show = false;
  }      
}

In myData directive require this controller:

require:'^myPanel'

And then, call controller function when you need

if (!scope.data){
  myPanelCtrl.hidePanel();
}

Look this Plunker example

Andrey
  • 161
  • 1
  • 3
0

The answers above where the parent directive's controller is required is a great one if there truly is a dependency. I had a similar problem to solve, but wanted to use the child directive within multiple parent directives or even without a parent directive, so here's what I did.

Your HTML.

<myPanel>
    <myData dataId={{dataId}}></myData>
</myPanel>

In your directive simply watch for changes to the attribute.

controller: function ($scope, $element, $attrs) {
    $attrs.$observe('dataId', function(dataId) { $scope.hide = true; } );
}

It's explicit and simple without forcing a dependency relationship where one may not exist. Hope this helps some people.

Darryl
  • 1,451
  • 1
  • 12
  • 19