![](/img/trans.png)
[英]Ember: Cant access hasMany relation programmatically while it works in handlebars template?
[英]Display the first item in hasMany ember relationship in handlebars template
我需要在hasMany关系中显示第一个项目
基本上一个线程可以有多个作者,但我需要只显示特定模板中的第一个
我有以下的json
{
threads: [
{
id: 1,
authors: [2,3]
}
],
authors: [
{
id: 2,
fullname: "foo"
},
{
id: 3,
fullname: "bar"
}
]
}
以及以下型号
App.Thread = DS.Model.extend({
authors: DS.hasMany('author')
});
App.Author = DS.Model.extend({
fullname: DS.attr('string')
});
现在在我的模板中,我想做一些像{{thread.authors[0].fullname}}
这样的东西,但它不起作用。 我根据把手语法尝试了thread.authors.0.fullname
但没有改变。
Thnx提前为您提供帮助
使用Ember.Enumerable的firstObject
:
{{thread.firstObject.fullName}}
如果要在很多地方使用它,最好将其定义为模型中的计算属性:
App.Thread = DS.Model.extend({
authors: DS.hasMany('author')
firstAuthor: Ember.computed.alias('authors.firstObject')
});
并在模板中使用它:
{{firstAuthor.name}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.