![](/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.