找到模型后,如何添加其他模型属性? (或者如何在setupController中访问路径的参数?
给出路线
this.resource('gallery', { path:'/gallery/:gallery_id' });
和路由器/routes/gallery.js
export default Ember.Route.extend({
model: function(params) {
return this.store.find('monkeys', { monkeyType: params.gallery_id });
//can I add an additional property to the returned model here?
},
setupController: function(controller, model) {
var pageTitle = 'something related to params.gallery_id';
//can I access route params in here?
this.controllerFor("application").set('pageTitle', pageTitle);
controller.set('model', model);
}
});
理想情况下,我想将应用程序控制器上的pageTitle
属性设置为某个gallery_id
特定字符串,而api服务不会返回该字符串。
api根据网址/monkeys?monkeyType=someId
{ "monkeys":[{ ... }, { ... }] }
答案 0 :(得分:1)
也许是这样的?
export default Em.Route.extend({
model: function(params) {
var model = this.store.find('monkeys', { monkeyType; params.gallery_id });
model.then(function(models) {
this.controllerFor('application').set('pageTitle', models.get('firstObject.name'));
}.bind(this));
return model;
}
});
确保您返回model
和 then
来电返回的承诺。 store.find()
会返回PromiseArray
,而then()
只会返回一个承诺。
答案 1 :(得分:0)
以下是我最终的结果:
export default Ember.Route.extend({
model: function(params) {
return return {
tag:params.gallery_id,
monkeys:[]
};
},
setupController: function(controller, model) {
var url = window.ENV.api + 'monkeys?monkeyType=' + model.tag;
if(model.monkeys.length === 0){
$.getJSON(url, function(json){
model.monkeys.pushObjects(json.monkeys);
});
}
this.controllerFor("application").set('pageTitle',
this.getTitle(model.tag));
controller.set('model', model);
},
getTitle: function(tag){
//some arbitrary non-api lookup
}
});
我不太热衷于这个解决方案,所以很高兴听到改进,或者可能是使用Ember Data的版本。