0

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...

4
  • scope should be $scope in the controller function. Commented Jun 3, 2014 at 19:30
  • Any updates on what you've tried for solving this? Commented Jun 5, 2014 at 4:37
  • So far I'm using $rootScope.$emit and it works, but I'm trying to get it working with your solution. What value do I put in the "empty-cart" attribute? Commented Jun 5, 2014 at 18:08
  • It should be the name of the function on the parent scope (ie. emptyCart). I just updated my answer with a demo. Commented Jun 6, 2014 at 16:02

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.