Disclamer:几天前我开始使用Ember.js
假设有这两个模型:
App.Question = DS.Model.extend({
text: DS.attr('string'),
answers: DS.hasMany('answer', {async: true})
});
App.Answer = DS.Model.extend({
question: DS.belongsTo('question'),
text: DS.attr('string')
});
由于某些原因,我得到了这个JSON(没有"答案"列表)
{
...
"questions": [
{"id": 1, "text": "Foo?"}, ...
]
}
在模板中,我想加载并仅在明确需要时显示答案
{{#each questions itemController="question"}}
<div class="answer-wrapper">
{{text}}
<button {{action "loadAnswers"}}>Load answers</button>
<ul>
{{#each answers}}
<li>{{text}}</li>
{{/each}}
</ul>
</div>
{{/each}}
如何在控制器的loadAnswer操作中执行此操作?
App.QuestionController = Ember.ObjectController.extend({
...
actions: {
loadAnswers: function() {
// programatically load answers
}
}
});
解决方法:我可以更改模板中的属性
{{#each loadedAnswers}}
<li>{{text}}</li>
{{/each}}
并正确定义动作
App.QuestionController = Ember.ObjectController.extend({
...
actions: {
loadAnswers: function() {
// or loaded with ajax...
this.set("loadedAnswers", [
{id: 1, text: "foo"},
{id: 2, text: "bar"}
]);
}
}
});
答案 0 :(得分:0)
您可以使用if语句包装模板的该部分。除非请求异步关系,否则不会获取异步关系。
App.QuestionController = Ember.ObjectController.extend({
showAnswers: false,
...
actions: {
loadAnswers: function() {
this.set('showAnswers', true);
}
}
});
{{#if showAnswers}}
<ul>
{{#each answers}}
<li>{{text}}</li>
{{/each}}
</ul>
{{/if}}