我不确定这是否真的可行,但我本质上想要反转 AngularJS 中的“&”隔离范围。这是一个Plunkr进行演示。
基本上,我设置了一个自定义指令来提供一些可重用的 HTML。它利用 ng-transclude
允许在其中呈现一些外部内容。但是,我发现了一种情况,我想从嵌入的代码部分访问在指令的隔离范围内设置的函数。
所以基本上我有一些看起来像的东西:
<div ng-controller="MainController">
<!-- The directive -->
<div some-custom-directive>
<!-- Button 1 that invokes a method within the controller scope -->
<button id="button1" ng-click="invoke1()">Invoke from Controller</button>
<!-- Button 2 that invokes a method on the isolate scope for the custom directive -->
<button id="button2" ng-click="invoke2()">Invoke from Isolate Scope</button>
</div>
</div>
有谁知道这是否真的可行?
更新
根据@Mark Rajcok 的回答,$scope
中的$$prevSibling
可用于从嵌入的内容中访问指令的隔离范围。但是,我已经更新了上面的 Plunkr 以在 ng-repeat
指令中尝试这样做,但这是行不通的。我假设重复中的项目不继承范围。
最佳答案
虽然可能,但我提出的解决方案是一种 hack,因为它使用范围内部变量 $$prevSibling
。
在您嵌入的内容中,您处于嵌入范围内。该指令的隔离范围和嵌入范围是兄弟。要从嵌入作用域进入隔离作用域,您可以使用 $$prevSibling
。 (要从隔离作用域到嵌入作用域,您可以使用 $$nextSibling
。)
所以,这个 hack 会起作用:
<a href="" ng-click="$$prevSibling.action()">Invoke the Directive Action</a>
要在 Controller 范围内调用方法,您需要指定使用 &
作为@ganaraj 已经演示过的方法:
<content-presenter controller-action="action()">
然后在你的指令中:
scope: { controllerAction: '&' },
template: ... +
'<button ng-click="controllerAction()">Trigger Ctrl action()</button>' ...
使用 ng-repeat(参见 Samuel 的评论),每个项目都会创建一个包含范围的子范围。在下图中,我只显示了一个 item
以保持图片较小。反转 $$prevSibling 的 $$nextSibling 棕色箭头。
因此,从 ng-repeat 子作用域获取在隔离作用域上定义的方法 action()
的方法是
<div ng-repeat="item in items" ng-click="$parent.$$prevSibling.action()">
Angular v1.3+ 更新:
从 Angular v1.3 开始,嵌入作用域现在是指令隔离作用域的子级——它们不再是兄弟。因此,要从嵌入范围到隔离范围,请使用 $parent
。
使用 ng-repeat,每个项目仍然创建嵌入范围的子范围:
但是要从 ng-repeat 子作用域获取在隔离作用域上定义的方法 action()
,我们现在使用
<div ng-repeat="item in items" ng-click="$parent.$parent.action()">
关于javascript - 访问指令的隔离范围与嵌入的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16171952/