fguillen
fguillen

Reputation: 38888

EmberJS, How access in a child template to the model in the parent controller

I have this router:

// app/router.js
Router.map(function() {
  this.route('battle', function(){
    this.route('combats');
  })
});

In the combats route I can access to the battle model easily using:

// app/routes/battle/combat.js
this.modelFor('battle');

But if I want to access to this model also in the combats template things start to be complicate:

// app/templates/battle/combats.hbs
<h1>Combats for Battle {{<how to access to the battle>.title}}</h1>

{{#each model as |combat|}}
  {{combat.date}}
{{/each}}

I have solved this sending properties to the combats Controller from the combats Route:

// app/routes/battle/combat.js
setupController: function(controller, model) {
  controller.set('content', model);
  controller.set('battle', this.modelFor('battle'));
}

But I don't know if it is the correct way, it looks too much indirect under my perspective, like that you have to make a long workaround to make this property available in the template.

Upvotes: 0

Views: 403

Answers (1)

Remi Smirra
Remi Smirra

Reputation: 2539

It depends on how generic you want your code to be. For your special usecase it might be appropriate to use the Ember.RSVP.hash in your model hook in combats.js like this:

model(){
    return Ember.RSVP.hash({
        combats: //here your combat.js model code,
        battle: this.modelFor('battle');
    })
}

Then you can remove your setupController function and rewrite your template to:

<h1>Combats for Battle {{model.battle.title}}</h1>

{{#each model.combats as |combat|}}
  {{combat.date}}
{{/each}}

Upvotes: 1

Related Questions