Angular指令中的单向绑定 [英] One-way binding in Angular directives

查看:135
本文介绍了Angular指令中的单向绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

官方 Angular 文档进行编译讨论单向绑定类型<.

在Angular 社区中,我看到@通常被称为单向绑定类型".

In the Angular community, I see @ commonly referred to as the "one-way binding type".

有什么作用?在我看来,@并不是真正的单向绑定,因为它只是计算表达式并设置字符串. <似乎与=更加相似,不同之处在于绑定仅是单向绑定.

What gives? The @ doesn't seem to me to be true one-way binding since it's just evaluating the expression and setting a string. The < seems to be more similar to = with the exception that the binding is only one-way.

我的猜测是,最近引入了<,这将解释为什么@过去被称为单向绑定类型. (虽然是种类,但不太准确)

My guess is that < was introduced recently which would explain why @ used to be referred to as the one-way binding type. (Which it kind of is, but not quite)

希望有更多Angular经验的人可以为我解决一切! :)

Hopefully someone with more Angular experience can set things straight for me! :)

更新: @aaronmallen评论并确认<是最近添加的(Angular 1.5).

Update: @aaronmallen commented and confirmed that < was added recently (Angular 1.5).

为进一步说明问题,我什么时候应该使用@<?

To further clarify things, when should I use @ vs <?

推荐答案

在Angular 1.x中有两种方式进行单向绑定,具体取决于您使用的版本

< 1.5

@绑定将来自父级的文字值绑定到隔离范围中.因此,您可以执行以下操作:

There are two ways of doing one way binding in Angular 1.x depending on which version you have

<1.5

@ binding binds a literal value from the parent into the isolate scope. So you can do this:

<cat name="Fluffy" age="12"></cat>

您可以将其视为绑定的一种方式.因为绑定的是文字,所以数据不会返回,因为没有东西要分配给它.

You can think of this as one way binding. Because you are binding a literal, the data won't come back out, because there's nothing for it to be assigned to.

在较旧的Angular版本(< 1.5)中,当我们需要单向绑定时,我们使用@加curlies {{}}. curlies在传输之前将表达式转换为文字,因此我们传入的是文字:

In older version of Angular (<1.5), we used @ plus curlies {{}} when we wanted one way binding. The curlies converted the expression to a literal before transport, so we were passing in a literal:

<cat name="{{$ctrl.catName}}" age="{{$ctrl.catAge}}"></cat>

因为花括号表达式被计算为文字,然后将其作为文字传递给指令.数据无法再次恢复,因为curly已被评估为字符串,因此没有任何要分配给该数据的数据.

Because the curly brace expression was evaluated to a literal, and then passed in as a literal to the directive. The data couldn't come back up again, because the curlies have been evaluated to a string, so there's nothing for the data to be assigned to.

您仍然会在许多教程中找到使用此方法的方法.现在它已经过时了,您应该避免使用它.

You'll still find this method used in many tutorials. It is now obsolete, and you should probably avoid it.

在1.5中,我们获得了<绑定.这使我们能够以一种没有冰壶的方式进行装订.我们现在可以执行以下操作:

In 1.5 we got < binding. This lets us one way bind without the curlies. We can now do this:

<cat name="$ctrl.catName" age="$ctrl.catAge"></cat>

=绑定不同,如果值在隔离区上更改,则更改不会反映在父级中.效果是一样的,但是语法要好得多.

Unlike = binding, if the value changes on the isolate, the change won't be reflected in the parent. The effect is the same, but the syntax is much nicer.

这篇关于Angular指令中的单向绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆