0
votes

I'd like to access a function from the parent => parent controller inside my directive (with the controllerAs notation). I'm using angular 1.3.14 I have the following structure:

  • Controller (with save function)
    • (Child) controller
      • Directive with a template (and isolated scope). Inside this template I have a button which should call the save function from the parent (parent) controller.

I don't want to call $scope.$parent.$parent.save(...) Does anyone has an idea?

Thanks in advance.

2
just use save:^ in your child directive's scope and pass in parent function in directive attribute of html. Or you can require parent controller in child directive.ABOS

2 Answers

0
votes

Use just $scope.save().

In Angular there is scope hierarchy and by calling $scope.save() directive will look in directive's scope, if there is no save() method, it will look in parent's scope and so on. One condition is to don't have isolated scope for directive.

0
votes

There is no good way to do this other than passing the desired function into the directive. This is what using & in an isolated scope declaration is for.

https://docs.angularjs.org/guide/directive

Of course there are easier ways if the function is just a utility function. You could just register a filter. But if you want the child directive to alter the state of the parent controller at some event then using & is the best solution.

If you need the child directive to pass arguments to the function that is being passed to it then you are going to need to use the feature associated with this sentence in the above documentation:

This is specified in the directive by calling close({message: 'closing for now'}). Then the local variable message will be available within the on-close expression.