角JS的双花括号和单花括号的区别?

时间:2013-07-26 10:06:20

标签: angularjs

我是这个角度世界的新手,我对使用双花括号{{}}感到困惑 和单个花括号{}或有时没有花括号用于包含像指令

中的表达式
  1. ng-class={expression}
  2. normal data binding like{{obj.key}}
  3. ng-hide='mydata==="red"'

3 个答案:

答案 0 :(得分:273)

{{}} - 双花括号:

{{}}是Angular表达式,当您希望将内容写入HTML时非常方便:

<div>
    {{planet.name == "Earth" ? "Yeah! We 're home!" : "Eh! Where 're we?"}}
</div>

<!-- with some directives like `ngSrc` -->
<img ng-src="http://www.example.com/gallery/{{hash}}"/>

<!-- set the title attribute -->
<div ng-attr-title="{{celebrity.name}}">...

<!-- set a custom attribute for your custom directive -->
<div custom-directive custom-attr="{{pizza.size}}"></div>

不要在已经表达的地方使用这些!

例如,指令ngClick将引号之间的任何内容视为表达式:

<!-- so dont do this! -->
<!-- <button ng-click="activate({{item}})">... -->  

{} - 单花括号:

我们知道

{}代表JavaScript中的对象。在这里,没有什么不同:

<div ng-init="distanceWalked = {mon:2, tue:2.5, wed:0.8, thu:3, fri:1.5, 
sat:2, sun:3}">

使用ngClassngStyle等指令接受地图:

<span ng-style="{'color' : 'red'}">{{viruses.length}} viruses found!</span>

<div ng-class="{'green' : vegetable == 'lettuce', 
'red' : vegetable == 'tomato'}">..

没有花括号:

正如已经提到的那样,只要在内部表达式中使用无支撑。很简单:

<div ng-if="zoo.enclosure.inmatesCount == 0">
    Alarm! All the monkeys have escaped!
</div>

答案 1 :(得分:3)

关于{{}}的另一件事 它也被用作观察者.. 请尽量避免提高性能

答案 2 :(得分:0)

我知道这是一篇过时的文章,可能与主题无关,但这是对@DonD和@GafrieldKlon的回应...

如果您要使用ng-bind指令,则似乎实际上放置了一个观察者,而在使用{{}}时,不是。话虽如此,我相信上面的@riyas答案仍然部分正确,因为避免 {{}}通常在性能上更好,但并非出于所述原因。< / p>

This answer到另一篇文章中对此进行了更详细的说明。

相关问题