AngularJS 指令绑定 & 简介

指令中独立scope 的 & 官方说明:

1. 绑定表达式

2. 经常用来绑定回调函数

 

诡异的地方在于,这个 & 某次听人说在子组件中是不能传值给callback的,好奇查了一下官方文档,更加诡异了:

We saw earlier how to use =attr in the scope 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's close function is called, thanks to ng-click. This call to close on the isolated scope actually evaluates the expression hideDialog(message) in the context of the original scope, thus running Controller's hideDialog 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 calling close({message: 'closing for now'}). Then the local variable message will be available within the on-close expression.

文档中的例子见下链接:

https://plnkr.co/edit/QRCZgkuBqmNEZfRYv9yh?p=preview

 

- 原文中加粗的地方说明是可以在独立 scope 的指令中传值给父级 scope 的

- 红色部分就是诡异之处:传值可以通过、传一个对象(用key表示本地变量)到包裹函数中,父级 scope 就能接收到这个对象中的 value

 

也可以看这个例子:

https://repl.it/HsOE/25

 

总结:

1. 有点像 ES6 中的解构赋值(Destructuring Assignment

2. 要想通过 & 给父级传值, 就要传对象,对象里面包含需要传的值的键值对

3. 最后传给 & 的表达式上还有声明 传的这个值的名称(类似形参的形式)

 

注: 上面的总结的颜色和原文对应

 

参考文档:

官方文档

egghead视频

posted @ 2017-05-11 16:37  savokiss  阅读(185)  评论(0编辑  收藏  举报