Question

I have a MainController and a nested Directive. I'm looking at this example to see how the communication works between controllers and directive, but mine doesn't seems to work.

Basically, I want to call a main controller scope function from a custom directive (button empty cart). See the plunkr example below.

Plukr: http://plnkr.co/edit/82STLkKxBK6htTnmnqlu?p=preview

Whenever I do console.log(scope.$apply("emptyCart()")), it's undefined for some reason.

Note: I'm trying to avoid $rootScope.broadcast as much as possible...

Was it helpful?

Solution

You're using isolate scope for the parent directive, so the child directive does not have access to the scope of the controller.

In order to provide the child directive with access to that scope function while maintaining isolation of the parent, you can add that function as a scope: { ... } property on the parent directive:

scope: {
  ...
  emptyCart: '='
}

and set the function name to the corresponding attribute on the parent directive's view declaration:

<div ... data-show="showPopup" empty-cart="emptyCart"></div>

Then you can skip all of the workarounds you've attempted to employ in your Plunker, and just set an ng-click on the child directive in order to fire the controller function:

sHTML = "<button ... ng-click='emptyCart()'>Empty cart</button>";

Demo

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top