2014-10-06 79 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可能会更容易,但是随着条件变得更加复杂,您可以隐藏计算属性中的更多工作。