[英]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). 我想从我指令内的parent => parent控制器访问一个函数(使用controllerAs表示法)。 I'm using angular 1.3.14 I have the following structure: 我正在使用angular 1.3.14,我具有以下结构:
I don't want to call $scope.$parent.$parent.save(...) Does anyone has an idea? 我不想打电话给$ scope。$ parent。$ parent.save(...)有人有想法吗?
Thanks in advance. 提前致谢。
Use just $scope.save(). 仅使用$ 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. 在Angular中有作用域层次结构 ,通过调用$ scope.save()指令将查找指令的作用域,如果没有save()方法,它将查找父级作用域,依此类推。 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 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'}). 在指令中通过调用close({message:'forsing now''})来指定。 Then the local variable message will be available within the on-close expression. 然后,局部变量消息将在闭合表达式中可用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.