我已经仔细阅读了AngularJS关于这个主题的文档,然后摆弄了一个指令。这是小提琴。
以下是一些相关片段:
来自HTML:
<窗格bi-title = "标题" title =“{{标题}}>{{文本}}> < /窗格
从窗格指令:
scope: {biTitle: '=', title: '@', bar: '='},
有几件事我不明白:
为什么我必须使用“{{title}}”与“@”和“title”与“=”?
我也可以直接访问父范围,而不装饰我的元素与属性?
文档说:“通常情况下,通过表达式将数据从孤立的作用域传递到父作用域是可取的”,但这似乎也适用于双向绑定。为什么表达式路由会更好呢?
我发现另一个小提琴,显示表达式解决方案太:http://jsfiddle.net/maxisam/QrCXh/
这里有很多很好的答案,但我想就@、=和&绑定之间的差异提供我的观点,这对我来说很有用。
这三种绑定都是通过元素属性将数据从你的父作用域传递到你指令的隔离作用域的方法:
@ binding is for passing strings.
These strings support {{}} expressions for interpolated values.
For example:
. The interpolated expression is evaluated against
directive's parent scope.
= binding is for two-way model binding. The model in parent scope
is linked to the model in the directive's isolated scope. Changes to
one model affects the other, and vice versa.
& binding is for passing a method into your directive's scope so that
it can be called within your directive. The method is pre-bound to
the directive's parent scope, and supports arguments. For example if the method is hello(name) in parent scope, then in
order to execute the method from inside your directive, you must
call $scope.hello({name:'world'})
我发现通过一个更短的描述来参考作用域绑定更容易记住这些区别:
@属性字符串绑定
=双向模型绑定
&回调方法绑定
这些符号还可以更清楚地说明作用域变量在指令实现中的含义:
@字符串
=模型
&方法
按用处排序(至少对我来说):
=
@
&
@ get作为字符串
这不会创建任何绑定。您只是获得作为字符串传入的单词
=双向绑定
控制器所做的更改将反映在指令所持有的引用中,反之亦然
&这个行为有点不同,因为作用域得到一个函数,返回传入的对象。我想这是成功的必要条件。小提琴应该能说明这一点。
调用此getter函数后,结果对象的行为如下:
如果传递了一个函数:那么该函数在父(控制器)闭包中被调用时执行
如果传入了一个非函数:简单地获取一个没有绑定的对象的本地副本
这把小提琴应该能演示它们是如何工作的。特别注意使用get…希望能更好地理解我所说的&