简体   繁体   中英

AngularJS - Access a parent controller from child -> child directive with the controllerAs notation

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM