我想宣布我的控制器要加载两个模型。
我没有使用model
,beforeModel
或afterModel
挂钩,因为:
loading
routes / templates 我在路线中使用setupController挂钩:
setupController: function(controller, model) {
var that = this;
controller.set('model', {
stations: that.store.find('station'),
packages: that.store.find('package'),
});
}
我的控制器是Ember.Controller
。
为了在Handlebars中迭代这些模型,我必须使用model.stations.content.content
,这让我觉得我做错了什么:
{{#each station in model.stations.content.content}}
// .....
{{/each}}
有没有更好的方法在控制器上设置这些模型或使用不同的控制器类型?
答案 0 :(得分:2)
@ MilkyWayJoe的方法绝对是正确的方法,如果你意识到如果你有一个大型模型或你的AJAX请求需要很长时间,你的UI将变为空白Ember will try to find a loading
process模型正在加载。
@Chaosekie提出了我的问题的答案,即等待承诺从商店加载模型以实现然后在控制器上设置属性。
即。在route
:
setupController: function(controller, model) {
this.store.find('station').then(function(stations) {
controller.set('stations',stations);
});
this.store.find('package').then(function(packages) {
controller.set('packages', packages);
});
}
这允许我们使用' normal'来迭代这两个模型。在把手中的方式:
{{#each package in packages}}
// ....
{{/each}}
{{#each station in stations}}
// ....
{{/each}}
答案 1 :(得分:1)
您可以更改模型以返回Ember.RSVP.hash
,它将充当承诺包,并且在哈希范围内填充属性stations
和{{ 1}}使用您的数据,因此当模型得到解决时,它会将该哈希模式设置为控制器中的模型:
packages
然后在你的模板中:
[...]
model: function() {
return Em.RSVP.hash({
stations: this.store.find('station'),
packages: this.store.find('package')
});
}
[...]
或
{{#each item in model.stations}}
<li>{{item.name}}</li>
{{/each}}
(见jsbin)
答案 2 :(得分:1)
您无需为模型创建新对象。
您可以在控制器中执行以下操作:
setupController: function(controller, model){
controller.set('model', model);
this.stations().then(function(value){
controller.set('stations', value);
});
}
电台在哪里:
stations: function() {
return this.store.find('station');
}
然后,您可以在模板中使用stations
,方法与使用模型相同。查看this example
但是控制器应该只装饰一个模型,您可以考虑创建嵌套路由(这将为您提供嵌套控制器)。