1
無盡的嘗試後,我希望有人找到我想要的線索。我知道在stackoverflow上有關於這個特定主題的很多問題。不過,我想我不會問同樣的問題。因爲我沒有找到我的具體挑戰的答案。Ember.js在模板中顯示hasMany數據有一個或多個結果
這裏是我的路由器:
App.Router.map(function() {
this.resource('article', {path: '/article/:id'});
this.resource('article.new', {path: "/article/new"});
});
路線
App.ArticleRoute = Ember.Route.extend({
model: function (params) {
return this.store.find('article', params.id);
}
});
App.ArticleNewRoute = Ember.Route.extend({
renderTemplate: function() {
this.render('article', {
controller: 'article.new'
});
},
model: function() {
return this.store.createRecord('article');
}
});
的模型
App.Category = DS.Model.extend({
name: DS.attr('string'),
image: DS.attr('string'),
categoryRelation: DS.belongsTo('category')
});
App.Article = DS.Model.extend({
name: DS.attr('string'),
category: DS.hasMany('category')
)};
返回JSON從服務器:
{
"articles":[
{
"id":1,
"name":"Car 1",
"category":[1,2],
{
"id":2,
"name":"Car 2",
"category":2,
],
"categorys":[ // note the added 's' when returning multiple items as per EmberJS convention
{
"id":1,
"name":"Oldtimers"
},
{
"id":2,
"name":"Classic"
}
],
}
現在的問題,因爲我嘗試在我的模板如下:
<script type="text/x-handlebars" data-template-name="article">
<div>
{{#each category in model}}
{{category.name}}<br>
{{name}}<br>
{{/each}}
</div>
</script>
我已經在模板中嘗試多種變化,這是我最後的代碼,這似乎正確。注意:對於id爲2的文章,如果只有一篇文章,模板也必須呈現。
編輯:我翻譯了一些代碼給你們。如果有拼寫錯誤,它們可能不在原始代碼中。
嗨馬爾西奧,非常感謝爲您的答案!但是,這不會爲單個項目工作。請參閱ID爲2的文章。我是否需要將單個項目作爲數組從服務器返回? – DelphiLynx
我已編輯你的小提琴看到錯誤:未捕獲TypeError:對象2沒有方法'everyProperty'':http://jsfiddle.net/snmR2/很明顯,它期望每個語句的數組。但是,是否可以更改每個行爲,以便它也會顯示單個項目? – DelphiLynx
是的,將''category':2'更改爲''category「:[2]'將解決問題,除非您無法控制服務器端,否則這是解決問題的簡單方法。 –