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

查看:17
本文介绍了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

@ binding 将一个文本值从父级绑定到隔离作用域中.所以你可以这样做:

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) 中,当我们想要单向绑定时,我们使用 @ 加上卷曲 {{}}.卷曲在传输之前将表达式转换为文字,因此我们传入的是文字:

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>

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

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天全站免登陆