2014-10-06 66 views
0

如何在EmberJs上的模板上連接字符串(或如何添加類)?EmberJS模板連接

ex。

<script type="text/x-handlebars"> 
// This div I want to add a class go, Is this the right way to do it? 
<div class="fly {{isGo}}">Fly now</div> 

// Or it's something like this? 
<div class="fly "{{isGo}} >Fly now</div> 
</script> 
+0

這在[guides]中有詳細記錄(http://emberjs.com/guides/templates/binding-element-class-names/) – MilkyWayJoe 2014-10-06 14:32:50

+0

http://emberjs.com/guides/templates/binding-element -class-names/ – 2014-10-06 14:36:24

回答

1

有這樣的灰燼指南中的完整論述:http://emberjs.com/guides/templates/binding-element-class-names/

但你會做這樣的:

<div {{bind-attr class="isGo"}}>Fly now</div> 

而在你的控制器:

App.MyController = Ember.ObjectController.extend({ 
    flightIsAGo: true, 
    isGo: function() { 
     return "fly"+this.get('flightIsAGo') ? ' isGo' : ''; 
    }.property('flightIsAGo') 
} 
+0

嗨,謝謝你的回覆。我明白了,我必須將它綁定到一個控制器中,但我只是想知道'關於這個'導出默認值',這是一個有效的表達式嗎? – meetmahpuppy 2014-10-06 14:42:38

+0

對不起,這是ES6格式,在傳統的JavaScript中你會使用'App.ThingController = Ember.ObjectController.extend ...'等我改變了答案。 – 2014-10-06 15:09:34

+0

我也建議這個http://emberjs.com/guides/views/customizing-a-views-element/ – melc 2014-10-06 18:16:16

0

bind-attr曾經是解決限制的好方法在Ember的渲染中。現在使用HTMLBars Ember建議我們從bind-attr移開,因爲我們有更強大的方法。

Ember 1.13不推薦使用bind-attr來支持新的語法。 http://emberjs.com/deprecations/v1.x/#toc_bind-attr

工作實例提出的兩種方法都可以在燼捻,這裏的行動中可以看出: https://ember-twiddle.com/38f69f01d2fd994af3b0965f10882005?openFiles=templates.application.hbs%2C

方法1

如果你想要做的內線組合你的車把模板您可以這樣做:

<div class={{concat "fly " isGo}}>Fly now</div> 

方法2

否則使用計算的屬性,如:

flyingClass: Ember.computed('isGo', function() { 
    // return a string with 'fly' and the value of 
    // isGo. Will be updated if isGo changes. 
    // Array values are created with space delimited by 
    // ['className', 'anotherClassName', 'lastClastName'].join(' '); 
    // => "className anotherClassName lastClassName" 
    let going = this.get('isGo') ? 'going' : '' 
    return ['fly', going].join(' '); 
    }) 

,然後在你的車把模板:

<div class={{flyingClass}}>Fly now</div> 

這兩種方法之間的主要區別取決於你希望你的關注點分離。現在做方法1可能會更容易,但是隨着條件變得更加複雜,您可以隱藏計算屬性中的更多工作。