AngularJS 指令绑定 & 简介
指令中独立scope 的 & 官方说明:
1. 绑定表达式
2. 经常用来绑定回调函数
诡异的地方在于,这个 & 某次听人说在子组件中是不能传值给callback的,好奇查了一下官方文档,更加诡异了:
We saw earlier how to use
=attr
in thescope
option, but in the above example, we're using&attr
instead. The&
binding allows a directive to trigger evaluation of an expression in the context of the original scope, at a specific time. Any legal expression is allowed, including an expression which contains a function call. Because of this,&
bindings are ideal for binding callback functions to directive behaviors.When the user clicks the
x
in the dialog, the directive'sclose
function is called, thanks tong-click.
This call toclose
on the isolated scope actually evaluates the expressionhideDialog(message)
in the context of the original scope, thus runningController
'shideDialog
function.Often it's desirable to pass data from the isolate scope via an expression to the parent scope, this can be done by passing a map of local variable names and values into the expression wrapper function. For example, the
hideDialog
function takes a message to display when the dialog is hidden. This is specified in the directive by callingclose({message: 'closing for now'})
. Then the local variablemessage
will be available within theon-close
expression.
文档中的例子见下链接:
https://plnkr.co/edit/QRCZgkuBqmNEZfRYv9yh?p=preview
- 原文中加粗的地方说明是可以在独立 scope 的指令中传值给父级 scope 的
- 红色部分就是诡异之处:传值可以通过、传一个对象(用key表示本地变量)到包裹函数中,父级 scope 就能接收到这个对象中的 value
也可以看这个例子:
总结:
1. 有点像 ES6 中的解构赋值(Destructuring Assignment)
2. 要想通过 & 给父级传值, 就要传对象,对象里面包含需要传的值的键值对
3. 最后传给 & 的表达式上还有声明 传的这个值的名称(类似形参的形式)
注: 上面的总结的颜色和原文对应
参考文档: